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.prototype.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.prototype.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/browser.html b/docs/browser.html index 36bfe3f1e..fe9ba6c90 100644 --- a/docs/browser.html +++ b/docs/browser.html @@ -91,7 +91,7 @@ },1700); } }, 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.prototype.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.prototype.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 50c625678..86c9d7eac 100644 --- a/docs/date.html +++ b/docs/date.html @@ -91,7 +91,7 @@ },1700); } }, false); - }
30 seconds of code Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.
Date
dayOfYear
Gets the day of the year from a
Dateobject.Use
new Date()andDate.prototype.getFullYear()to get the first day of the year as aDateobject, subtract it from the provideddateand divide with the milliseconds in each day to get the result. UseMath.floor()to appropriately round the resulting day count to an integer.const dayOfYear = date => + }
30 seconds of code Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.
Date
dayOfYear
Gets the day of the year from a
Dateobject.Use
new Date()andDate.prototype.getFullYear()to get the first day of the year as aDateobject, subtract it from the provideddateand divide with the milliseconds in each day to get the result. UseMath.floor()to appropriately round the resulting day count to an integer.const dayOfYear = date => Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24);dayOfYear(new Date()); // 272formatDuration
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.prototype.filter()to keep only non-zero values. UseArray.prototype.map()to create the string for each value, pluralizing appropriately. UseString.prototype.join(', ')to combine the values into a string.const formatDuration = ms => { diff --git a/docs/function.html b/docs/function.html index ca48c82e0..140561c05 100644 --- a/docs/function.html +++ b/docs/function.html @@ -91,7 +91,7 @@ },1700); } }, 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/index.html b/docs/index.html index 34e27fa4e..aea484332 100644 --- a/docs/index.html +++ b/docs/index.html @@ -91,7 +91,7 @@ },1700); } }, 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.prototype.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.prototype.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]); // trueallEqual
Check if all elements in an array are equal.
Use
Array.prototype.every()to check if all the elements of the array are the same as the first one.const allEqual = arr => arr.every(val => val === arr[0]); diff --git a/docs/math.html b/docs/math.html index 22ca4aedf..d4a8f2a38 100644 --- a/docs/math.html +++ b/docs/math.html @@ -91,7 +91,7 @@ },1700); } }, 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.prototype.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 b5bd260a5..90f1f3c1e 100644 --- a/docs/node.html +++ b/docs/node.html @@ -91,7 +91,7 @@ },1700); } }, 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' @@ -137,8 +137,38 @@ console.log< ) );hashNode(JSON.stringify({ a: 'a', b: [1, 2, 3, 4], foo: { c: 'bar' } })).then(console.log); // '04aa106279f5977f59f9067fa9712afc4aedc6f5862a8defc34552d8c7206393' +isDuplexStream
Checks if the given argument is a duplex (readable and writable) stream.
Check if the value is different from
null, usetypeofto check if a value is of typeobjectand thepipeproperty is of typefunction. Additionally check if thetypeofthe_read,_writeand_readableState,_writableStateproperties arefunctionandobjectrespectively.const isDuplexStream = val => + val !== null && + typeof val === 'object' && + typeof val.pipe === 'function' && + typeof val.pipe === 'function' && + typeof val._read === 'function' && + typeof val._readableState === 'object' && + typeof val._write === 'function' && + typeof val._writableState === 'object'; +const Stream = require('stream'); +isDuplexStream(new Stream.Duplex()); // true +isReadableStream
Checks if the given argument is a readable stream.
Check if the value is different from
null, usetypeofto check if the value is of typeobjectand thepipeproperty is of typefunction. Additionally check if thetypeofthe_readand_readableStateproperties arefunctionandobjectrespectively.const isReadableStream = val => + val !== null && + typeof val === 'object' && + typeof val.pipe === 'function' && + typeof val._read === 'function' && + typeof val._readableState === 'object'; +const fs = require('fs'); +isReadableStream(fs.createReadStream('test.txt')); // true +isStream
Checks if the given argument is a stream.
Check if the value is different from
null, usetypeofto check if the value is of typeobjectand thepipeproperty is of typefunction.const isStream = val => val !== null && typeof val === 'object' && typeof val.pipe === 'function'; +const fs = require('fs'); +isStream(fs.createReadStream('test.txt')); // trueisTravisCI
Checks if the current environment is Travis CI.
Checks if the current environment has the
TRAVISandCIenvironment variables (reference).const isTravisCI = () => 'TRAVIS' in process.env && 'CI' in process.env;isTravisCI(); // true (if code is running on Travis CI) +isWritableStream
Checks if the given argument is a writable stream.
Check if the value is different from
null, usetypeofto check if the value is of typeobjectand thepipeproperty is of typefunction. Additionally check if thetypeofthe_writeand_writableStateproperties arefunctionandobjectrespectively.const isWritableStream = val => + val !== null && + typeof val === 'object' && + typeof val.pipe === 'function' && + typeof val._write === 'function' && + typeof val._writableState === 'object'; +const fs = require('fs'); +isWritableStream(fs.createWriteStream('test.txt')); // trueJSONToFile
Writes a JSON object to a file.
Use
fs.writeFile(), template literals andJSON.stringify()to write ajsonobject to a.jsonfile.const fs = require('fs'); const JSONToFile = (obj, filename) => fs.writeFile(`${filename}.json`, JSON.stringify(obj, null, 2)); diff --git a/docs/object.html b/docs/object.html index 66396c8e6..15f6448e7 100644 --- a/docs/object.html +++ b/docs/object.html @@ -91,7 +91,7 @@ },1700); } }, 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.prototype.forEach()to return afunctionthat usesFunction.prototype.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.prototype.forEach()to return afunctionthat usesFunction.prototype.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 ecba2e8b4..670520bc8 100644 --- a/docs/string.html +++ b/docs/string.html @@ -91,7 +91,7 @@ },1700); } }, 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.prototype.toUpperCase()to capitalize first letter,...restto get array of characters after first letter and thenArray.prototype.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 12dcf006c..035c78ffb 100644 --- a/docs/type.html +++ b/docs/type.html @@ -91,7 +91,7 @@ },1700); } }, 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.prototype.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 cac9c8720..b16730f0f 100644 --- a/docs/utility.html +++ b/docs/utility.html @@ -91,7 +91,7 @@ },1700); } }, 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.prototype.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.prototype.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);
