how to use the cond function from lodash in javascript

The _.cond() function from lodash is a utility function for creating a function that evaluates a series of conditions and returns a result based on the first condition that is true. It takes an array of arrays, where each sub-array represents a condition/result pair.

Here's an example usage of _.cond():

index.tsx
const func = _.cond([
  [_.matches({ 'a': 1 }), () => 'matches A'],
  [_.conforms({ 'b': _.isNumber }), () => 'matches B'],
  [_.stubTrue, () => 'matches C']
]);

console.log(func({ 'a': 1, 'b': 2 })); // 'matches A'
console.log(func({ 'a': 0, 'b': '1' })); // 'matches B'
console.log(func({ 'a': '2', 'b': '1' })); // 'matches C'
331 chars
10 lines

In this example, we're creating a function func that evaluates three conditions. The first checks if the object passed in has a property 'a' with value 1 using _.matches(). If true, func returns the string 'matches A'. The second condition checks if the object conforms to an object where the property 'b' is of type Number using _.conforms(). If that is true, func returns the string 'matches B'. Finally, the _.stubTrue function is called (which always returns true), and func returns the string 'matches C'.

We can then pass in objects to func and it will evaluate the conditions and return the corresponding string as the result.

gistlibby LogSnag