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 ] @@ -126,6 +126,8 @@ Object.assigeveryNth([1, 2, 3, 4, 5, 6], 2); // [ 2, 4, 6 ]filterNonUnique
Filters out the non-unique values in an array.
Use
Array.filter()for an array containing only the unique values.const filterNonUnique = arr => arr.filter(i => arr.indexOf(i) === arr.lastIndexOf(i));filterNonUnique([1, 2, 2, 3, 4, 4, 5]); // [1,3,5] +findLast
Returns the last element for which the provided function returns a truthy value.
Use
Array.filter()to remove elements for whichfnreturns falsey values,Array.slice(-1)to get the last one.const findLast = (arr, fn) => arr.filter(fn).slice(-1); +findLast([1, 2, 3, 4], n => n % 2 === 1); // 3flatten
Flattens an array up to the specified depth.
Use recursion, decrementing
depthby 1 for each level of depth. UseArray.reduce()andArray.concat()to merge elements or arrays. Base case, fordepthequal to1stops recursion. Omit the second argument,depthto flatten only to a depth of1(single flatten).const flatten = (arr, depth = 1) => depth != 1 ? arr.reduce((a, v) => a.concat(Array.isArray(v) ? flatten(v, depth - 1) : v), []) @@ -1194,6 +1196,7 @@ Logs: { + const newPost = { "userId": 1, "id": 1337, diff --git a/snippets/findLast.md b/snippets/findLast.md index 9dfa824d3..901920049 100644 --- a/snippets/findLast.md +++ b/snippets/findLast.md @@ -9,5 +9,5 @@ const findLast = (arr, fn) => arr.filter(fn).slice(-1); ``` ```js -findLast([1, 2, 3, 4], n => n % 2 === 1) // 3 +findLast([1, 2, 3, 4], n => n % 2 === 1); // 3 ``` diff --git a/snippets/httpPost.md b/snippets/httpPost.md index 4976ff767..15246d648 100644 --- a/snippets/httpPost.md +++ b/snippets/httpPost.md @@ -32,6 +32,7 @@ const httpPost = (url, callback, data = null, err = console.error) => { + const newPost = { "userId": 1, "id": 1337,