Skip to content

Commit

Permalink
refactor defaults logic
Browse files Browse the repository at this point in the history
  • Loading branch information
ianstormtaylor committed Nov 23, 2017
1 parent ad12e0c commit 313df01
Showing 1 changed file with 9 additions and 20 deletions.
29 changes: 9 additions & 20 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,6 @@ function superstruct(options = {}) {
})

return (value) => {
value = toValue(value, defaults)

if (!isOptional && value === undefined) {
throw new ValueRequiredError({ type })
}
Expand Down Expand Up @@ -82,8 +80,6 @@ function superstruct(options = {}) {
const type = 'array'

return (value) => {
value = toValue(value, defaults)

if (value === undefined) {
throw new ValueRequiredError({ type })
} else if (!is.array(value)) {
Expand Down Expand Up @@ -128,7 +124,6 @@ function superstruct(options = {}) {
}

return (value) => {
value = toValue(value, defaults)
let isUndefined = false

if (value === undefined) {
Expand Down Expand Up @@ -201,7 +196,15 @@ function superstruct(options = {}) {
throw new Error(`A struct schema definition must be a string, array or object, but you passed: ${schema}`)
}

return s
return (value) => {
if (value === undefined) {
value = typeof defaults === 'function'
? defaults()
: cloneDeep(defaults)
}

return s(value)
}
}

/**
Expand All @@ -211,20 +214,6 @@ function superstruct(options = {}) {
return struct
}

/**
* Resolve a `defaults` and a `value` into a value.
*
* @param {Any} value
* @param {Any} defaults
* @return {Any}
*/

function toValue(value, defaults) {
if (value !== undefined) return value
if (typeof defaults === 'function') return defaults()
return cloneDeep(defaults)
}

/**
* Export the factory and the factory creator.
*
Expand Down

0 comments on commit 313df01

Please sign in to comment.