4 ms·
It's tomorrow somewhere… /** * These functions are intended to be used with array iteration methods * ------------------- * // Example data:
by smichel17 6y ago
It's tomorrow somewhere…
/**
* These functions are intended to be used with array iteration methods
* -------------------
* // Example data:
* let e1 = { a: 1, b: 2, c: "C" };
* let e2 = { a: 2, b: 12, c: "D" };
* let myArray = [ e1, e2 ];
*
* // Basic usage, matching a constant
* myArray.filter(match({a: 1})); // [ e1 ]
* myArray.filter(match({a: 3})); // [ ]
*
* // Matching multiple properties
* myArray.filter(match({ a: 1, c: "C" })); // [ e1 ]
* myArray.filter(match({ a: 1, c: "D" })); // [ ]
* myArray.filter(matchAny({ a: 1, c: "D" })); // [ e1, e2 ]
*
* // If a function is provided, return the result of the function
* // called with the corresponding property as its argument.
* let belowTen = n => n < 10;
* myArray.filter(match({ a: belowTen, b: belowTen })); // [ e1 ]
* myArray.filter(matchAny({ a: belowTen, b: belowTen })); // [ e1, e2 ]
*
*/
export const match = o1 => o2 => Object.entries(o1).every(
([k, v]) => typeof v === "function" ? v(o2[k]) : o2[k] === v
);
export const matchAny = o1 => o2 => Object.entries(o1).some(
([k, v]) => typeof v === "function" ? v(o2[k]) : o2[k] === v
);