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 ] @@ -93,6 +93,13 @@ Object.assigchunk([1, 2, 3, 4, 5], 2); // [[1,2],[3,4],[5]]compact
Removes falsey values from an array.
Use
Array.filter()to filter out falsey values (false,null,0,"",undefined, andNaN).const compact = arr => arr.filter(Boolean);compact([0, 1, false, 2, '', 3, 'a', 'e' * 23, NaN, 's', 34]); // [ 1, 2, 3, 'a', 's', 34 ] +countBy
Groups the elements of an array based on the given function and returns the count of elements in each group.
Use
Array.map()to map the values of an array to a function or property name. UseArray.reduce()to create an object, where the keys are produced from the mapped results.const countBy = (arr, fn) => + arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val, i) => { + acc[val] = (acc[val] || 0) + 1; + return acc; + }, {}); +countBy([6.1, 4.2, 6.3], Math.floor); // {4: 1, 6: 2} +countBy(['one', 'two', 'three'], 'length'); // {3: 2, 5: 1}countOccurrences
Counts the occurrences of a value in an array.
Use
Array.reduce()to increment a counter each time you encounter the specific value inside the array.const countOccurrences = (arr, val) => arr.reduce((a, v) => (v === val ? a + 1 : a + 0), 0);countOccurrences([1, 1, 2, 1, 2, 3], 1); // 3deepFlatten
Deep flattens an array.
Use recursion. Use
Array.concat()with an empty array ([]) and the spread operator (...) to flatten an array. Recursively flatten each element that is an array.const deepFlatten = arr => [].concat(...arr.map(v => (Array.isArray(v) ? deepFlatten(v) : v))); @@ -131,8 +138,8 @@ Object.assig .reverse() .forEach(callback);forEachRight([1, 2, 3, 4], val => console.log(val)); // '4', '3', '2', '1' -groupBy
Groups the elements of an array based on the given function.
Use
Array.map()to map the values of an array to a function or property name. UseArray.reduce()to create an object, where the keys are produced from the mapped results.const groupBy = (arr, func) => - arr.map(typeof func === 'function' ? func : val => val[func]).reduce((acc, val, i) => { +groupBy
Groups the elements of an array based on the given function.
Use
Array.map()to map the values of an array to a function or property name. UseArray.reduce()to create an object, where the keys are produced from the mapped results.const groupBy = (arr, fn) => + arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val, i) => { acc[val] = (acc[val] || []).concat(arr[i]); return acc; }, {}); @@ -620,8 +627,11 @@ document.body📋 Copy to clipboardMath
average
Returns the average of an of two or more numbers.
Use
Array.reduce()to add each value to an accumulator, initialized with a value of0, divide by thelengthof the array.const average = (...nums) => [...nums].reduce((acc, val) => acc + val, 0) / nums.length;average(...[1, 2, 3]); // 2 average(1, 2, 3); // 2 -averageBy
Returns the average of an array, after mapping each element to a value using the provided function.
Use
Array.map()to map each element to the value returned byfn,Array.reduce()to add each value to an accumulator, initialized with a value of0, divide by thelengthof the array.const averageBy = (arr, fn) => arr.map(fn).reduce((acc, val) => acc + val, 0) / arr.length; +averageBy
Returns the average of an array, after mapping each element to a value using the provided function.
Use
Array.map()to map each element to the value returned byfn,Array.reduce()to add each value to an accumulator, initialized with a value of0, divide by thelengthof the array.const averageBy = (arr, fn) => + arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val) => acc + val, 0) / + arr.length;averageBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], o => o.n); // 5 +averageBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], 'n'); // 5clampNumber
Clamps
numwithin the inclusive range specified by the boundary valuesaandb.If
numfalls within the range, returnnum. Otherwise, return the nearest number in the range.const clampNumber = (num, a, b) => Math.max(Math.min(num, Math.max(a, b)), Math.min(a, b));clampNumber(2, 3, 5); // 3 clampNumber(1, -1, -5); // -1 @@ -723,16 +733,18 @@ own individual rating by supplying it as the third argument.luhnCheck('4485275742308327'); // true luhnCheck(6011329933655299); // false luhnCheck(123456789); // false -maxBy
Returns the maximum value of an array, after mapping each element to a value using the provided function.
Use
Array.map()to map each element to the value returned byfn,Math.max()to get the maximum value.const maxBy = (arr, fn) => Math.max(...arr.map(fn)); +maxBy
Returns the maximum value of an array, after mapping each element to a value using the provided function.
Use
Array.map()to map each element to the value returned byfn,Math.max()to get the maximum value.const maxBy = (arr, fn) => Math.max(...arr.map(typeof fn === 'function' ? fn : val => val[fn]));maxBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], o => o.n); // 8 +maxBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], 'n'); // 8median
Returns the median of an array of numbers.
Find the middle of the array, use
Array.sort()to sort the values. Return the number at the midpoint iflengthis odd, otherwise the average of the two middle numbers.const median = arr => { const mid = Math.floor(arr.length / 2), nums = [...arr].sort((a, b) => a - b); return arr.length % 2 !== 0 ? nums[mid] : (nums[mid - 1] + nums[mid]) / 2; };median([5, 6, 50, 1, -5]); // 5 -minBy
Returns the minimum value of an array, after mapping each element to a value using the provided function.
Use
Array.map()to map each element to the value returned byfn,Math.min()to get the maximum value.const minBy = (arr, fn) => Math.min(...arr.map(fn)); +minBy
Returns the minimum value of an array, after mapping each element to a value using the provided function.
Use
Array.map()to map each element to the value returned byfn,Math.min()to get the maximum value.const minBy = (arr, fn) => Math.min(...arr.map(typeof fn === 'function' ? fn : val => val[fn]));minBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], o => o.n); // 8 +minBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], 'n'); // 8percentile
Uses the percentile formula to calculate how many numbers in the given array are less or equal to the given value.
Use
Array.reduce()to calculate how many numbers are below the value and how many are the same value and apply the percentile formula.const percentile = (arr, val) => 100 * arr.reduce((acc, v) => acc + (v < val ? 1 : 0) + (v === val ? 0.5 : 0), 0) / arr.length;percentile([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 6); // 55 @@ -772,8 +784,10 @@ own individual rating by supplying it as the third argument. standardDeviation([10, 2, 38, 23, 38, 23, 21], true); // 12.29899614287479 (population)sum
Returns the sum of two or more numbers/arrays.
Use
Array.reduce()to add each value to an accumulator, initialized with a value of0.const sum = (...arr) => [...arr].reduce((acc, val) => acc + val, 0);sum(...[1, 2, 3, 4]); // 10 -sumBy
Returns the sum of an array, after mapping each element to a value using the provided function.
Use
Array.map()to map each element to the value returned byfn,Array.reduce()to add each value to an accumulator, initialized with a value of0.const sumBy = (arr, fn) => arr.map(fn).reduce((acc, val) => acc + val, 0); +sumBy
Returns the sum of an array, after mapping each element to a value using the provided function.
Use
Array.map()to map each element to the value returned byfn,Array.reduce()to add each value to an accumulator, initialized with a value of0.const sumBy = (arr, fn) => + arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val) => acc + val, 0);sumBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], o => o.n); // 20 +sumBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], 'n'); // 20sumPower
Returns the sum of the powers of all the numbers from
starttoend(both inclusive).Use
Array.fill()to create an array of all the numbers in the target range,Array.map()and the exponent operator (**) to raise them topowerandArray.reduce()to add them together. Omit the second argument,power, to use a default power of2. Omit the third argument,start, to use a default starting value of1.const sumPower = (end, power = 2, start = 1) => Array(end + 1 - start) .fill(0) @@ -1179,6 +1193,7 @@ Logs: { + const newPost = { "userId": 1, "id": 1337, diff --git a/snippets/averageBy.md b/snippets/averageBy.md index e31117182..026634993 100644 --- a/snippets/averageBy.md +++ b/snippets/averageBy.md @@ -6,7 +6,8 @@ Use `Array.map()` to map each element to the value returned by `fn`, `Array.redu ```js const averageBy = (arr, fn) => - arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val) => acc + val, 0) / arr.length; + arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val) => acc + val, 0) / + arr.length; ``` ```js diff --git a/snippets/httpPost.md b/snippets/httpPost.md index e9e6d1e70..4976ff767 100644 --- a/snippets/httpPost.md +++ b/snippets/httpPost.md @@ -31,6 +31,7 @@ const httpPost = (url, callback, data = null, err = console.error) => { + const newPost = { "userId": 1, "id": 1337, diff --git a/snippets/maxBy.md b/snippets/maxBy.md index 9186dd009..14d3b2aeb 100644 --- a/snippets/maxBy.md +++ b/snippets/maxBy.md @@ -5,11 +5,10 @@ Returns the maximum value of an array, after mapping each element to a value usi Use `Array.map()` to map each element to the value returned by `fn`, `Math.max()` to get the maximum value. ```js -const maxBy = (arr, fn) => - Math.max(...arr.map(typeof fn === 'function' ? fn : val => val[fn])); +const maxBy = (arr, fn) => Math.max(...arr.map(typeof fn === 'function' ? fn : val => val[fn])); ``` ```js maxBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], o => o.n); // 8 -maxBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }],'n'); // 8 +maxBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], 'n'); // 8 ``` diff --git a/snippets/minBy.md b/snippets/minBy.md index 9f735119c..594d83f5e 100644 --- a/snippets/minBy.md +++ b/snippets/minBy.md @@ -5,8 +5,7 @@ Returns the minimum value of an array, after mapping each element to a value usi Use `Array.map()` to map each element to the value returned by `fn`, `Math.min()` to get the maximum value. ```js -const minBy = (arr, fn) => - Math.min(...arr.map(typeof fn === 'function' ? fn : val => val[fn])); +const minBy = (arr, fn) => Math.min(...arr.map(typeof fn === 'function' ? fn : val => val[fn])); ``` ```js