Adapter
ary
Creates a function that accepts up to n arguments, ignoring any additional arguments.
Call the provided function, fn, with up to n arguments, using Array.slice(0,n) and the spread operator (...).
const ary = (fn, n) => (...args) => fn(...args.slice(0, n)); + }
30 seconds of code Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.
Adapter
ary
Creates a function that accepts up to
narguments, ignoring any additional arguments.Call the provided function,
fn, with up tonarguments, usingArray.slice(0,n)and the spread operator (...).const ary = (fn, n) => (...args) => fn(...args.slice(0, n));const firstTwoMax = ary(Math.max, 2); [[2, 6, 'a'], [8, 4, 6], [10]].map(x => firstTwoMax(...x)); // [6, 8, 10]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); diff --git a/docs/array.html b/docs/array.html index 19302df41..2d75e14e6 100644 --- a/docs/array.html +++ b/docs/array.html @@ -79,7 +79,7 @@ document.getElementById('doc-drawer-checkbox').checked = false; } }, false); - }
30 seconds of code Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.
Array
all
Returns
trueif the provided predicate function returnstruefor all elements in a collection,falseotherwise.Use
Array.every()to test if all elements in the collection returntruebased onfn. Omit the second argument,fn, to useBooleanas a default.const all = (arr, fn = Boolean) => arr.every(fn); + }
30 seconds of code Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.
Array
all
Returns
trueif the provided predicate function returnstruefor all elements in a collection,falseotherwise.Use
Array.every()to test if all elements in the collection returntruebased onfn. Omit the second argument,fn, to useBooleanas a default.const all = (arr, fn = Boolean) => arr.every(fn);all([4, 2, 3], x => x > 1); // true all([1, 2, 3]); // trueany
Returns
trueif the provided predicate function returnstruefor at least one element in a collection,falseotherwise.Use
Array.some()to test if any elements in the collection returntruebased onfn. Omit the second argument,fn, to useBooleanas a default.const any = (arr, fn = Boolean) => arr.some(fn); @@ -148,6 +148,18 @@everyNth([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] +filterNonUniqueBy
Filters out the non-unique values in an array, based on a provided comparator function.
Use
Array.filter()andArray.every()for an array containing only the unique values, based on the comparator function,fn. The comparator function takes four arguments: the values of the two elements being compared and their indexes.const filterNonUniqueBy = (arr, fn) => + arr.filter((v, i) => arr.every((x, j) => (i == j) == fn(v, x, i, j))); +filterNonUniqueBy( + [ + { id: 0, value: 'a' }, + { id: 1, value: 'b' }, + { id: 2, value: 'c' }, + { id: 1, value: 'd' }, + { id: 0, value: 'e' } + ], + (a, b) => a.id == b.id +); // [ { id: 2, value: 'c' } ]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.pop()to get the last one.const findLast = (arr, fn) => arr.filter(fn).pop();findLast([1, 2, 3, 4], n => n % 2 === 1); // 3findLastIndex
Returns the index of the last element for which the provided function returns a truthy value.
Use
Array.map()to map each element to an array with its index and value. UseArray.filter()to remove elements for whichfnreturns falsey values,Array.pop()to get the last one.const findLastIndex = (arr, fn) => @@ -521,6 +533,36 @@ managers; //unionWith([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] +uniqueElementsBy
Returns all unique values of an array, based on a provided comparator function.
Use
Array.reduce()andArray.some()for an array containing only the first unique occurence of each value, based on the comparator function,fn. The comparator function takes two arguments: the values of the two elements being compared.const uniqueElementsBy = (arr, fn) => + arr.reduce((acc, v) => { + if (!acc.some(x => fn(v, x))) acc.push(v); + return acc; + }, []); +uniqueElementsBy( + [ + { id: 0, value: 'a' }, + { id: 1, value: 'b' }, + { id: 2, value: 'c' }, + { id: 1, value: 'd' }, + { id: 0, value: 'e' } + ], + (a, b) => a.id == b.id +); // [ { id: 0, value: 'a' }, { id: 1, value: 'b' }, { id: 2, value: 'c' } ] +uniqueElementsByRight
Returns all unique values of an array, based on a provided comparator function.
Use
Array.reduce()andArray.some()for an array containing only the last unique occurence of each value, based on the comparator function,fn. The comparator function takes two arguments: the values of the two elements being compared.const uniqueElementsByRight = (arr, fn) => + arr.reduceRight((acc, v) => { + if (!acc.some(x => fn(v, x))) acc.push(v); + return acc; + }, []); +uniqueElementsByRight( + [ + { id: 0, value: 'a' }, + { id: 1, value: 'b' }, + { id: 2, value: 'c' }, + { id: 1, value: 'd' }, + { id: 0, value: 'e' } + ], + (a, b) => a.id == b.id +); // [ { id: 0, value: 'e' }, { id: 1, value: 'd' }, { id: 2, value: 'c' } ]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), diff --git a/docs/browser.html b/docs/browser.html index ab1aa8a61..220dbc674 100644 --- a/docs/browser.html +++ b/docs/browser.html @@ -79,7 +79,7 @@ document.getElementById('doc-drawer-checkbox').checked = false; } }, false); - }
30 seconds of code Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.
Browser
arrayToHtmlList
Converts the given array elements into
<li>tags and appends them to the list of the given id.Use
Array.map(),document.querySelector(), and an anonymous inner closure to create a list of html tags.const arrayToHtmlList = (arr, listID) => + }
30 seconds of code Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.
Browser
arrayToHtmlList
Converts the given array elements into
<li>tags and appends them to the list of the given id.Use
Array.map(),document.querySelector(), and an anonymous inner closure to create a list of html tags.const arrayToHtmlList = (arr, listID) => (el => ( (el = document.querySelector('#' + listID)), (el.innerHTML += arr.map(item => `<li>${item}</li>`).join('')) diff --git a/docs/date.html b/docs/date.html index c170bfc0e..2e6c2f511 100644 --- a/docs/date.html +++ b/docs/date.html @@ -79,7 +79,7 @@ document.getElementById('doc-drawer-checkbox').checked = false; } }, false); - }
30 seconds of code Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.
Date
formatDuration
Returns the human readable format of the given number of milliseconds.
Divide
mswith the appropriate values to obtain the appropriate values forday,hour,minute,secondandmillisecond. UseObject.entries()withArray.filter()to keep only non-zero values. UseArray.map()to create the string for each value, pluralizing appropriately. UseString.join(', ')to combine the values into a string.const formatDuration = ms => { + }
30 seconds of code Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.
Date
formatDuration
Returns the human readable format of the given number of milliseconds.
Divide
mswith the appropriate values to obtain the appropriate values forday,hour,minute,secondandmillisecond. UseObject.entries()withArray.filter()to keep only non-zero values. UseArray.map()to create the string for each value, pluralizing appropriately. UseString.join(', ')to combine the values into a string.const formatDuration = ms => { if (ms < 0) ms = -ms; const time = { day: Math.floor(ms / 86400000), diff --git a/docs/function.html b/docs/function.html index 7d4ad8c60..a85d65dbd 100644 --- a/docs/function.html +++ b/docs/function.html @@ -79,7 +79,7 @@ document.getElementById('doc-drawer-checkbox').checked = false; } }, false); - }
30 seconds of code Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.
Function
attempt
Attempts to invoke a function with the provided arguments, returning either the result or the caught error object.
Use a
try... catchblock to return either the result of the function or an appropriate error.const attempt = (fn, ...args) => { + }
30 seconds of code Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.
Function
attempt
Attempts to invoke a function with the provided arguments, returning either the result or the caught error object.
Use a
try... catchblock to return either the result of the function or an appropriate error.const attempt = (fn, ...args) => { try { return fn(...args); } catch (e) { diff --git a/docs/math.html b/docs/math.html index 1a44be510..23b744e3a 100644 --- a/docs/math.html +++ b/docs/math.html @@ -79,7 +79,7 @@ document.getElementById('doc-drawer-checkbox').checked = false; } }, false); - }
30 seconds of code Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.
Math
approximatelyEqual
Checks if two numbers are approximately equal to each other.
Use
Math.abs()to compare the absolute difference of the two values toepsilon. Omit the third parameter,epsilon, to use a default value of0.001.const approximatelyEqual = (v1, v2, epsilon = 0.001) => Math.abs(v1 - v2) < epsilon; + }
30 seconds of code Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.
Math
approximatelyEqual
Checks if two numbers are approximately equal to each other.
Use
Math.abs()to compare the absolute difference of the two values toepsilon. Omit the third parameter,epsilon, to use a default value of0.001.const approximatelyEqual = (v1, v2, epsilon = 0.001) => Math.abs(v1 - v2) < epsilon;approximatelyEqual(Math.PI / 2.0, 1.5708); // trueaverage
Returns the average 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 diff --git a/docs/node.html b/docs/node.html index 01234348e..cbdecc4a7 100644 --- a/docs/node.html +++ b/docs/node.html @@ -79,7 +79,7 @@ document.getElementById('doc-drawer-checkbox').checked = false; } }, false); - }
30 seconds of code Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.
Node
atob
Decodes a string of data which has been encoded using base-64 encoding.
Create a
Bufferfor the given string with base-64 encoding and useBuffer.toString('binary')to return the decoded string.const atob = str => new Buffer(str, 'base64').toString('binary'); + }
30 seconds of code Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.
Node
atob
Decodes a string of data which has been encoded using base-64 encoding.
Create a
Bufferfor the given string with base-64 encoding and useBuffer.toString('binary')to return the decoded string.const atob = str => new Buffer(str, 'base64').toString('binary');atob('Zm9vYmFy'); // 'foobar'btoa
Creates a base-64 encoded ASCII string from a String object in which each character in the string is treated as a byte of binary data.
Create a
Bufferfor the given string with binary encoding and useBuffer.toString('base64')to return the encoded string.const btoa = str => new Buffer(str, 'binary').toString('base64');btoa('foobar'); // 'Zm9vYmFy' diff --git a/docs/object.html b/docs/object.html index c9246fe40..02b3c89e1 100644 --- a/docs/object.html +++ b/docs/object.html @@ -79,7 +79,7 @@ document.getElementById('doc-drawer-checkbox').checked = false; } }, false); - }
30 seconds of code Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.
Object
bindAll
Binds methods of an object to the object itself, overwriting the existing method.
Use
Array.forEach()to return afunctionthat usesFunction.apply()to apply the given context (obj) tofnfor each function specified.const bindAll = (obj, ...fns) => + }
30 seconds of code Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.
Object
bindAll
Binds methods of an object to the object itself, overwriting the existing method.
Use
Array.forEach()to return afunctionthat usesFunction.apply()to apply the given context (obj) tofnfor each function specified.const bindAll = (obj, ...fns) => fns.forEach( fn => ( (f = obj[fn]), diff --git a/docs/string.html b/docs/string.html index 38b288680..52a0ac13c 100644 --- a/docs/string.html +++ b/docs/string.html @@ -79,7 +79,7 @@ document.getElementById('doc-drawer-checkbox').checked = false; } }, false); - }
30 seconds of code Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.
String
byteSize
Returns the length of a string in bytes.
Convert a given string to a
BlobObject and find itssize.const byteSize = str => new Blob([str]).size; + }
30 seconds of code Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.
String
byteSize
Returns the length of a string in bytes.
Convert a given string to a
BlobObject and find itssize.const byteSize = str => new Blob([str]).size;byteSize('😀'); // 4 byteSize('Hello World'); // 11capitalize
Capitalizes the first letter of a string.
Use array destructuring and
String.toUpperCase()to capitalize first letter,...restto get array of characters after first letter and thenArray.join('')to make it a string again. Omit thelowerRestparameter to keep the rest of the string intact, or set it totrueto convert to lowercase.const capitalize = ([first, ...rest], lowerRest = false) => diff --git a/docs/type.html b/docs/type.html index e46362e4e..772eace27 100644 --- a/docs/type.html +++ b/docs/type.html @@ -79,7 +79,7 @@ document.getElementById('doc-drawer-checkbox').checked = false; } }, false); - }
30 seconds of code Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.
Type
getType
Returns the native type of a value.
Returns lowercased constructor name of value,
"undefined"or"null"if value isundefinedornull.const getType = v => + }
30 seconds of code Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.
Type
getType
Returns the native type of a value.
Returns lowercased constructor name of value,
"undefined"or"null"if value isundefinedornull.const getType = v => v === undefined ? 'undefined' : v === null ? 'null' : v.constructor.name.toLowerCase();getType(new Set([1, 2, 3])); // 'set'is
Checks if the provided value is of the specified type.
Ensure the value is not
undefinedornullusingArray.includes(), and compare theconstructorproperty on the value withtypeto check if the provided value is of the specifiedtype.const is = (type, val) => ![, null].includes(val) && val.constructor === type; diff --git a/docs/utility.html b/docs/utility.html index 13bf49d16..0ed292bfb 100644 --- a/docs/utility.html +++ b/docs/utility.html @@ -79,7 +79,7 @@ document.getElementById('doc-drawer-checkbox').checked = false; } }, false); - }
30 seconds of code Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.
Utility
castArray
Casts the provided value as an array if it's not one.
Use
Array.isArray()to determine ifvalis an array and return it as-is or encapsulated in an array accordingly.const castArray = val => (Array.isArray(val) ? val : [val]); + }
30 seconds of code Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.
Utility
castArray
Casts the provided value as an array if it's not one.
Use
Array.isArray()to determine ifvalis an array and return it as-is or encapsulated in an array accordingly.const castArray = val => (Array.isArray(val) ? val : [val]);castArray('foo'); // ['foo'] castArray([1]); // [1]cloneRegExp
Clones a regular expression.
Use
new RegExp(),RegExp.sourceandRegExp.flagsto clone the given regular expression.const cloneRegExp = regExp => new RegExp(regExp.source, regExp.flags); diff --git a/snippets/filterNonUniqueBy.md b/snippets/filterNonUniqueBy.md index a2abdfe6a..61b9fcc27 100644 --- a/snippets/filterNonUniqueBy.md +++ b/snippets/filterNonUniqueBy.md @@ -7,18 +7,18 @@ The comparator function takes four arguments: the values of the two elements bei ```js const filterNonUniqueBy = (arr, fn) => - arr.filter((v, i) => arr.every((x, j) => i == j == fn(v, x, i, j))); + arr.filter((v, i) => arr.every((x, j) => (i == j) == fn(v, x, i, j))); ``` ```js filterNonUniqueBy( - [ - { id: 0, value: 'a' }, - { id: 1, value: 'b' }, - { id: 2, value: 'c' }, - { id: 1, value: 'd' }, - { id: 0, value: 'e' }, - ], - (a, b) => a.id == b.id + [ + { id: 0, value: 'a' }, + { id: 1, value: 'b' }, + { id: 2, value: 'c' }, + { id: 1, value: 'd' }, + { id: 0, value: 'e' } + ], + (a, b) => a.id == b.id ); // [ { id: 2, value: 'c' } ] ``` diff --git a/snippets/uniqueElementsBy.md b/snippets/uniqueElementsBy.md index 08bf7b19a..2751da4e8 100644 --- a/snippets/uniqueElementsBy.md +++ b/snippets/uniqueElementsBy.md @@ -7,21 +7,21 @@ The comparator function takes two arguments: the values of the two elements bein ```js const uniqueElementsBy = (arr, fn) => - arr.reduce((acc, v) => { - if (!acc.some(x => fn(v, x))) acc.push(v); - return acc; - }, []); + arr.reduce((acc, v) => { + if (!acc.some(x => fn(v, x))) acc.push(v); + return acc; + }, []); ``` ```js uniqueElementsBy( - [ - { id: 0, value: 'a' }, - { id: 1, value: 'b' }, - { id: 2, value: 'c' }, - { id: 1, value: 'd' }, - { id: 0, value: 'e' }, - ], - (a, b) => a.id == b.id + [ + { id: 0, value: 'a' }, + { id: 1, value: 'b' }, + { id: 2, value: 'c' }, + { id: 1, value: 'd' }, + { id: 0, value: 'e' } + ], + (a, b) => a.id == b.id ); // [ { id: 0, value: 'a' }, { id: 1, value: 'b' }, { id: 2, value: 'c' } ] ``` diff --git a/snippets/uniqueElementsByRight.md b/snippets/uniqueElementsByRight.md index 791c9621a..fcf98c604 100644 --- a/snippets/uniqueElementsByRight.md +++ b/snippets/uniqueElementsByRight.md @@ -7,21 +7,21 @@ The comparator function takes two arguments: the values of the two elements bein ```js const uniqueElementsByRight = (arr, fn) => - arr.reduceRight((acc, v) => { - if (!acc.some(x => fn(v, x))) acc.push(v); - return acc; - }, []); + arr.reduceRight((acc, v) => { + if (!acc.some(x => fn(v, x))) acc.push(v); + return acc; + }, []); ``` ```js uniqueElementsByRight( - [ - { id: 0, value: 'a' }, - { id: 1, value: 'b' }, - { id: 2, value: 'c' }, - { id: 1, value: 'd' }, - { id: 0, value: 'e' }, - ], - (a, b) => a.id == b.id + [ + { id: 0, value: 'a' }, + { id: 1, value: 'b' }, + { id: 2, value: 'c' }, + { id: 1, value: 'd' }, + { id: 0, value: 'e' } + ], + (a, b) => a.id == b.id ); // [ { id: 0, value: 'e' }, { id: 1, value: 'd' }, { id: 2, value: 'c' } ] ```
