Check property

JavaScript, Function, Object · Nov 1, 2020

Creates a function that will invoke a predicate function for the specified property on a given object.

  • Return a curried function, that will invoke predicate for the specified prop on obj and return a 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 = checkProp(u => u.active && !u.disabled, 'user');

validUserSession(session); // false

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

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

More like this

  • JavaScript Objects

    Handle JavaScript objects with ease, using the snippets and tips in this ES6 collection.

    Collection · 113 snippets

  • Bind function context

    Creates a function that invokes fn with a given context, optionally prepending any additional supplied parameters to the arguments.

    JavaScript, Function · Oct 18, 2020

  • Rearrange function arguments

    Creates a function that invokes the provided function with its arguments arranged according to the specified indexes.

    JavaScript, Function · Oct 22, 2020

  • Bind object method

    Creates a function that invokes a method at a key in an object, with optional additional parameters.

    JavaScript, Function · Oct 18, 2020