Adapter
call
Given a key and a set of arguments, call them when given a context. Primarily useful in composition.
Use a closure to call a stored key with stored arguments.
const call = (key, ...args) => context => context[key](...args); + }
30 seconds of code Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.
Adapter
call
Given a key and a set of arguments, call them when given a context. Primarily useful in composition.
Use a closure to call a stored key with stored arguments.
const call = (key, ...args) => context => context[key](...args);Promise.resolve([1, 2, 3]) .then(call('map', x => 2 * x)) .then(console.log); //[ 2, 4, 6 ] @@ -187,6 +187,13 @@ Object.assig return a.filter(x => s.has(x)); };intersection([1, 2, 3], [4, 3, 2]); // [2,3] +intersectionBy
Returns a list of elements that exist in both arrays, after applying the provided function to each array element of both.
Create a
Setby applyingfnto all elements inb, then useArray.filter()onato only keep elements, which produce values contained inbwhenfnis applied to them.const intersectionBy = (a, b, fn) => { + const s = new Set(b.map(x => fn(x))); + return a.filter(x => s.has(fn(x))); +}; +intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor); // [2.1] +intersectionWith
Returns a list of elements that exist in both arrays, using a provided comparator function.
Use
Array.filter()andArray.findIndex()in combination with the provided comparator to determine intersecting values.const intersectionWith = (a, b, comp) => a.filter(x => b.findIndex(y => comp(x, y)) !== -1); +intersectionWith([1, 1.2, 1.5, 3, 0], [1.9, 3, 0, 3.9], (a, b) => Math.round(a) === Math.round(b)); // [1.5, 3, 0]isSorted
Returns
1if the array is sorted in ascending order,-1if it is sorted in descending order or0if it is not sorted.Calculate the ordering
directionfor the first two elements. UseObject.entries()to loop over array objects and compare them in pairs. Return0if thedirectionchanges or thedirectionif the last element is reached.const isSorted = arr => { const direction = arr[0] > arr[1] ? -1 : 1; for (let [i, val] of arr.entries()) diff --git a/snippets/intersectionWith.md b/snippets/intersectionWith.md index ae5483c47..4aa7e0874 100644 --- a/snippets/intersectionWith.md +++ b/snippets/intersectionWith.md @@ -5,8 +5,7 @@ Returns a list of elements that exist in both arrays, using a provided comparato Use `Array.filter()` and `Array.findIndex()` in combination with the provided comparator to determine intersecting values. ```js -const intersectionWith = (a, b, comp) => - a.filter(x => b.findIndex(y => comp(x, y)) !== -1); +const intersectionWith = (a, b, comp) => a.filter(x => b.findIndex(y => comp(x, y)) !== -1); ``` ```js