Files
30-seconds-of-code/snippets/checkProp.md
Robert Mennell 54ed736e28 Create checkProp.md
Adds a simple `checkProp` factory function for re-usable utility predicates.

The reason the predicate comes before the prop is to signify the predicate will be called with the prop, however I have no desire to make that a hard requirement. Order can easily be changed.
2019-03-16 18:53:00 -07:00

869 B

checkProp

Given a predicate function and a prop string this curried function will then take an object to inspect by calling the property and passing it to the predicate.

It summons prop on obj and passes it to a provided predicate function and returns a masked boolean

const checkProp = (predicate, prop) => obj => !!predicate(obj[prop])
const lengthIs4 = checkProp(l => l === 4, 'length')
lengthIs4([]) // false
lengthIs4([1,2,3,4]) // true
lengthIs4(new Set([1,2,3,4]) // false (Set uses Size, not length)

const session = { user: {} }
const validUserSession = checkProps(u => u.active && !u.disabled, 'user')

validUserSession(session) // false

session.user.active = true
validUserSession(session) // true

const noLength(l => l === undefined, 'length')
noLength([]) // false
noLength({}) // true
noLength(new Set()) // true