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 ] @@ -361,6 +361,14 @@ Object.assig takeRight([1, 2, 3]); // [3]union
Returns every element that exists in any of the two arrays once.
Create a
Setwith all values ofaandband convert to an array.const union = (a, b) => Array.from(new Set([...a, ...b]));union([1, 2, 3], [4, 3, 2]); // [1,2,3,4] +unionBy
Returns every element that exists in any of the two arrays once, after applying the provided function to each array element of both.
Create a
Setby applying allfnto all values ofa. Create aSetfromaand all elements inbwhose value, after applyingfndoes not match a value in the previously created set. Return the last set converted to an array.const unionBy = (a, b, fn) => { + const s = new Set(a.map(v => fn(v))); + return Array.from(new Set([...a, ...b.filter(x => !s.has(fn(x)))])); +}; +unionBy([2.1], [1.2, 2.3], Math.floor); // [2.1, 1.2] +unionWith
Returns every element that exists in any of the two arrays once, using a provided comparator function.
Create a
Setwith all values ofaand values inbfor which the comparator finds no matches ina, usingArray.findIndex().const unionWith = (a, b, comp) => + Array.from(new Set([...a, ...b.filter(x => a.findIndex(y => comp(x, y)) === -1)])); +unionWith([1, 1.2, 1.5, 3, 0], [1.9, 3, 0, 3.9], (a, b) => Math.round(a) === Math.round(b)); // [1, 1.2, 1.5, 3, 0, 3.9]uniqueElements
Returns all unique values of an array.
Use ES6
Setand the...restoperator to discard all duplicated values.const uniqueElements = arr => [...new Set(arr)];uniqueElements([1, 2, 2, 3, 4, 4, 5]); // [1,2,3,4,5]without
Filters out the elements of an array, that have one of the specified values.
Use
Array.filter()to create an array excluding(using!Array.includes()) all given values.(For a snippet that mutates the original array see
pull)const without = (arr, ...args) => arr.filter(v => !args.includes(v)); diff --git a/snippets/unionWith.md b/snippets/unionWith.md index dbfee938b..0243a12aa 100644 --- a/snippets/unionWith.md +++ b/snippets/unionWith.md @@ -6,9 +6,7 @@ Create a `Set` with all values of `a` and values in `b` for which the comparator ```js const unionWith = (a, b, comp) => - Array.from( - new Set([...a, ...b.filter(x => a.findIndex(y => comp(x, y)) === -1)]) - ); + Array.from(new Set([...a, ...b.filter(x => a.findIndex(y => comp(x, y)) === -1)])); ``` ```js