3 ms·
It's nice for any type of list iteration. I'll share my "match" function (for use when filtering) when I'm at my computer tomorrow.
by smichel17 6y ago
It's nice for any type of list iteration. I'll share my "match" function (for use when filtering) when I'm at my computer tomorrow.
- smichel17 6y agoIt'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 );