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 ] @@ -371,6 +371,15 @@ Object.assigunionWith([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] +unzip
Creates an array of arrays, ungrouping the elements in an array produced by zip.
Use
Math.max.apply()to get the longest subarray in the array,Array.map()to make each element an array. UseArray.reduce()andArray.forEach()to map grouped values to individual arrays.const unzip = arr => + arr.reduce( + (acc, val) => (val.forEach((v, i) => acc[i].push(v)), acc), + Array.from({ + length: Math.max(...arr.map(x => x.length)) + }).map(x => []) + ); +unzip([['a', 1, true], ['b', 2, false]]); //[['a', 'b'], [1, 2], [true, false]] +unzip([['a', 1, true], ['b', 2]]); //[['a', 'b'], [1, 2], [true]]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));without([2, 1, 2, 3], 1, 2); // [3]zip
Creates an array of elements, grouped based on the position in the original arrays.
Use
Math.max.apply()to get the longest array in the arguments. Creates an array with that length as return value and useArray.from()with a map-function to create an array of grouped elements. If lengths of the argument-arrays vary,undefinedis used where no value could be found.const zip = (...arrays) => { diff --git a/snippets/unzip.md b/snippets/unzip.md index 9c01f9285..96503871e 100644 --- a/snippets/unzip.md +++ b/snippets/unzip.md @@ -10,7 +10,7 @@ const unzip = arr => arr.reduce( (acc, val) => (val.forEach((v, i) => acc[i].push(v)), acc), Array.from({ - length: Math.max(...arr.map(x => x.length)), + length: Math.max(...arr.map(x => x.length)) }).map(x => []) ); ```