untitled notebook

node v6.17.1
version: 1.0.0
endpointsharetweet
const isObjectOf = schema => obj => { Object.keys(schema).forEach(key => { const value = obj[key] const pred = schema[key] try { if (pred(value) === false) { throw new Error('invalid') } } catch(err) { throw new Error(`${key} ${err.message}`) } }) return true } const isArrayOf = pred => arr => { arr.forEach((value, i) => { try { if (pred(value) === false) { throw new Error('invalid') } } catch(err) { throw new Error(`[${i}] ${err.message}`) } }) } const isRequired = pred => value => { if (value === undefined) { throw new Error('missing') } else { return pred(value) } } const isOptional = pred => value => { if (value === undefined) { return true } else { return pred(value) } } const isString = isOptional(s => typeof s === 'string') const isNumber = isOptional(n => typeof n === 'number') const isMyType = isObjectOf({ foo: isString, bar: isRequired(isNumber), arr: isArrayOf(isNumber) }) isMyOtherType = isObjectOf({ baz: isString, myType: isRequired(isMyType) }) isMyOtherType({ baz: 'dop', myType:{ // foo: 'fo', bar: 3, arr: [3, 3] } })
Loading…

no comments

    sign in to comment