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 ] @@ -380,6 +380,16 @@ Object.assig );unzip([['a', 1, true], ['b', 2, false]]); //[['a', 'b'], [1, 2], [true, false]] unzip([['a', 1, true], ['b', 2]]); //[['a', 'b'], [1, 2], [true]] +unzipWithadvanced
Creates an array of elements, ungrouping the elements in an array produced by zip and applying the provided function.
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. UseArray.map()and the spread operator (...) to applyfnto each individual group of elements.const unzipWith = (arr, fn) => + 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 => []) + ) + .map(val => fn(...val)); +unzipWith([[1, 10, 100], [2, 20, 200]], (...args) => args.reduce((acc, v) => acc + v, 0)); // [3, 30, 300]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/unzipWith.md b/snippets/unzipWith.md index 75314d0b8..c474a2e84 100644 --- a/snippets/unzipWith.md +++ b/snippets/unzipWith.md @@ -12,7 +12,7 @@ const unzipWith = (arr, fn) => .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 => []) ) .map(val => fn(...val));