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 ] @@ -335,6 +335,21 @@ Object.assig return [...a.filter(x => !sB.has(x)), ...b.filter(x => !sA.has(x))]; };symmetricDifference([1, 2, 3], [1, 2, 4]); // [3,4] +symmetricDifferenceBy
Returns the symmetric difference between two arrays, after applying the provided function to each array element of both.
Create a
Setby applyingfnto each array's elements, then useArray.filter()on each of them to only keep values not contained in the other.const symmetricDifferenceBy = (a, b, fn) => { + const sA = new Set(a.map(v => fn(v))), + sB = new Set(b.map(v => fn(v))); + return [...a.filter(x => !sB.has(fn(x))), ...b.filter(x => !sA.has(fn(x)))]; +}; +symmetricDifferenceBy([2.1, 1.2], [2.3, 3.4], Math.floor); // [ 1.2, 3.4 ] +symmetricDifferenceWith
Returns the symmetric difference between two arrays, using a provided function as a comparator.
Use
Array.filter()andArray.findIndex()to find the appropriate values.const symmetricDifferenceWith = (arr, val, comp) => [ + ...arr.filter(a => val.findIndex(b => comp(a, b)) === -1), + ...val.filter(a => arr.findIndex(b => comp(a, b)) === -1) +]; +symmetricDifferenceWith( + [1, 1.2, 1.5, 3, 0], + [1.9, 3, 0, 3.9], + (a, b) => Math.round(a) === Math.round(b) +); // [1, 1.2, 3.9]tail
Returns all elements in an array except for the first one.
Return
Array.slice(1)if the array'slengthis more than1, otherwise, return the whole array.const tail = arr => (arr.length > 1 ? arr.slice(1) : arr);tail([1, 2, 3]); // [2,3] tail([1]); // [1] diff --git a/snippets/symmetricDifferenceWith.md b/snippets/symmetricDifferenceWith.md index 67d081ccd..5eab574fa 100644 --- a/snippets/symmetricDifferenceWith.md +++ b/snippets/symmetricDifferenceWith.md @@ -7,10 +7,14 @@ Use `Array.filter()` and `Array.findIndex()` to find the appropriate values. ```js const symmetricDifferenceWith = (arr, val, comp) => [ ...arr.filter(a => val.findIndex(b => comp(a, b)) === -1), - ...val.filter(a => arr.findIndex(b => comp(a, b)) === -1), + ...val.filter(a => arr.findIndex(b => comp(a, b)) === -1) ]; ``` ```js -symmetricDifferenceWith([1, 1.2, 1.5, 3, 0], [1.9, 3, 0, 3.9], (a, b) => Math.round(a) === Math.round(b)); // [1, 1.2, 3.9] +symmetricDifferenceWith( + [1, 1.2, 1.5, 3, 0], + [1.9, 3, 0, 3.9], + (a, b) => Math.round(a) === Math.round(b) +); // [1, 1.2, 3.9] ```