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 ] @@ -173,6 +173,12 @@ Object.assig join(['pen', 'pineapple', 'apple', 'pen']); // "pen,pineapple,apple,pen"last
Returns the last element in an array.
Use
arr.length - 1to compute the index of the last element of the given array and returning it.const last = arr => arr[arr.length - 1];last([1, 2, 3]); // 3 +longestItem
Takes any number of iterable objects or objects with a
lengthproperty and returns the longest one.Use
Array.sort()to sort all arguments bylength, return the first (longest) one.const longestItem = (...vals) => [...vals].sort((a, b) => b.length - a.length)[0]; +longestItem('this', 'is', 'a', 'testcase'); // 'testcase' +longestItem(...['a', 'ab', 'abc']); // 'abc' +longestItem(...['a', 'ab', 'abc'], 'abcd'); // 'abcd' +longestItem([1, 2, 3], [1, 2], [1, 2, 3, 4, 5]); // [1, 2, 3, 4, 5] +longestItem([1, 2, 3], 'foobar'); // 'foobar'mapObject
Maps the values of an array to an object using a function, where the key-value pairs consist of the original value as the key and the mapped value.
Use an anonymous inner function scope to declare an undefined memory space, using closures to store a return value. Use a new
Arrayto store the array with a map of the function over its data set and a comma operator to return a second step, without needing to move from one context to another (due to closures and order of operations).const mapObject = (arr, fn) => (a => ( (a = [arr, arr.map(fn)]), a[0].reduce((acc, val, ind) => ((acc[val] = a[1][ind]), acc), {}) @@ -1132,10 +1138,4 @@ console.log< yesNo('yes'); // true yesNo('No'); // false yesNo('Foo', true); // true -Uncategorized
longestItem
Takes any number of iterable objects or objects with a
lengthproperty and returns the longest one.Use
Array.sort()to sort all arguments bylength, return the first (longest) one.const longestItem = (...vals) => [...vals].sort((a, b) => b.length - a.length)[0]; -longestItem('this', 'is', 'a', 'testcase'); // 'testcase' -longestItem(...['a', 'ab', 'abc']); // 'abc' -longestItem(...['a', 'ab', 'abc'], 'abcd'); // 'abcd' -longestItem([1, 2, 3], [1, 2], [1, 2, 3, 4, 5]); // [1, 2, 3, 4, 5] -longestItem([1, 2, 3], 'foobar'); // 'foobar' -