Apply new format to snippets and template
This commit is contained in:
@ -5,7 +5,9 @@ tags: array,intermediate
|
||||
|
||||
Explain briefly what the snippet does.
|
||||
|
||||
Explain briefly how the snippet works.
|
||||
- Explain briefly how the snippet works.
|
||||
- Use bullet points for your snippet's explanation.
|
||||
- Try to explain everything briefly but clearly.
|
||||
|
||||
```js
|
||||
const functionName = arguments =>
|
||||
|
||||
@ -5,10 +5,10 @@ tags: string,array,intermediate
|
||||
|
||||
Converts a comma-separated values (CSV) string to a 2D array.
|
||||
|
||||
Use `Array.prototype.slice()` and `Array.prototype.indexOf('\n')` to remove the first row (title row) if `omitFirstRow` is `true`.
|
||||
Use `String.prototype.split('\n')` to create a string for each row, then `String.prototype.split(delimiter)` to separate the values in each row.
|
||||
Omit the second argument, `delimiter`, to use a default delimiter of `,`.
|
||||
Omit the third argument, `omitFirstRow`, to include the first row (title row) of the CSV string.
|
||||
- Use `Array.prototype.slice()` and `Array.prototype.indexOf('\n')` to remove the first row (title row) if `omitFirstRow` is `true`.
|
||||
- Use `String.prototype.split('\n')` to create a string for each row, then `String.prototype.split(delimiter)` to separate the values in each row.
|
||||
- Omit the second argument, `delimiter`, to use a default delimiter of `,`.
|
||||
- Omit the third argument, `omitFirstRow`, to include the first row (title row) of the CSV string.
|
||||
|
||||
```js
|
||||
const CSVToArray = (data, delimiter = ',', omitFirstRow = false) =>
|
||||
|
||||
@ -6,10 +6,10 @@ tags: string,array,object,advanced
|
||||
Converts a comma-separated values (CSV) string to a 2D array of objects.
|
||||
The first row of the string is used as the title row.
|
||||
|
||||
Use `Array.prototype.slice()` and `Array.prototype.indexOf('\n')` and `String.prototype.split(delimiter)` to separate the first row (title row) into values.
|
||||
Use `String.prototype.split('\n')` to create a string for each row, then `Array.prototype.map()` and `String.prototype.split(delimiter)` to separate the values in each row.
|
||||
Use `Array.prototype.reduce()` to create an object for each row's values, with the keys parsed from the title row.
|
||||
Omit the second argument, `delimiter`, to use a default delimiter of `,`.
|
||||
- Use `Array.prototype.slice()` and `Array.prototype.indexOf('\n')` and `String.prototype.split(delimiter)` to separate the first row (title row) into values.
|
||||
- Use `String.prototype.split('\n')` to create a string for each row, then `Array.prototype.map()` and `String.prototype.split(delimiter)` to separate the values in each row.
|
||||
- Use `Array.prototype.reduce()` to create an object for each row's values, with the keys parsed from the title row.
|
||||
- Omit the second argument, `delimiter`, to use a default delimiter of `,`.
|
||||
|
||||
```js
|
||||
const CSVToJSON = (data, delimiter = ',') => {
|
||||
|
||||
@ -5,7 +5,7 @@ tags: node,json,intermediate
|
||||
|
||||
Writes a JSON object to a file.
|
||||
|
||||
Use `fs.writeFileSync()`, template literals and `JSON.stringify()` to write a `json` object to a `.json` file.
|
||||
- Use `fs.writeFileSync()`, template literals and `JSON.stringify()` to write a `json` object to a `.json` file.
|
||||
|
||||
```js
|
||||
const fs = require('fs');
|
||||
|
||||
@ -5,10 +5,10 @@ tags: array,string,object,advanced
|
||||
|
||||
Converts an array of objects to a comma-separated values (CSV) string that contains only the `columns` specified.
|
||||
|
||||
Use `Array.prototype.join(delimiter)` to combine all the names in `columns` to create the first row.
|
||||
Use `Array.prototype.map()` and `Array.prototype.reduce()` to create a row for each object, substituting non-existent values with empty strings and only mapping values in `columns`.
|
||||
Use `Array.prototype.join('\n')` to combine all rows into a string.
|
||||
Omit the third argument, `delimiter`, to use a default delimiter of `,`.
|
||||
- Use `Array.prototype.join(delimiter)` to combine all the names in `columns` to create the first row.
|
||||
- Use `Array.prototype.map()` and `Array.prototype.reduce()` to create a row for each object, substituting non-existent values with empty strings and only mapping values in `columns`.
|
||||
- Use `Array.prototype.join('\n')` to combine all rows into a string.
|
||||
- Omit the third argument, `delimiter`, to use a default delimiter of `,`.
|
||||
|
||||
```js
|
||||
const JSONtoCSV = (arr, columns, delimiter = ',') =>
|
||||
|
||||
@ -5,7 +5,7 @@ tags: string,math,intermediate
|
||||
|
||||
Converts the values of RGB components to a hexadecimal color code.
|
||||
|
||||
Convert given RGB parameters to hexadecimal string using bitwise left-shift operator (`<<`) and `toString(16)`, then `String.padStart(6,'0')` to get a 6-digit hexadecimal value.
|
||||
- Convert given RGB parameters to hexadecimal string using bitwise left-shift operator (`<<`) and `toString(16)`, then `String.padStart(6,'0')` to get a 6-digit hexadecimal value.
|
||||
|
||||
```js
|
||||
const RGBToHex = (r, g, b) => ((r << 16) + (g << 8) + b).toString(16).padStart(6, '0');
|
||||
|
||||
@ -5,7 +5,7 @@ tags: string,regexp,advanced
|
||||
|
||||
Joins all given URL segments together, then normalizes the resulting URL.
|
||||
|
||||
Use `String.prototype.join('/')` to combine URL segments, then a series of `String.prototype.replace()` calls with various regexps to normalize the resulting URL (remove double slashes, add proper slashes for protocol, remove slashes before parameters, combine parameters with `'&'` and normalize first parameter delimiter).
|
||||
- Use `String.prototype.join('/')` to combine URL segments, then a series of `String.prototype.replace()` calls with various regexps to normalize the resulting URL (remove double slashes, add proper slashes for protocol, remove slashes before parameters, combine parameters with `'&'` and normalize first parameter delimiter).
|
||||
|
||||
```js
|
||||
const URLJoin = (...args) =>
|
||||
|
||||
@ -5,7 +5,7 @@ tags: browser,random,intermediate
|
||||
|
||||
Generates a UUID in a browser.
|
||||
|
||||
Use `crypto` API to generate a UUID, compliant with [RFC4122](https://www.ietf.org/rfc/rfc4122.txt) version 4.
|
||||
- Use `crypto` API to generate a UUID, compliant with [RFC4122](https://www.ietf.org/rfc/rfc4122.txt) version 4.
|
||||
|
||||
```js
|
||||
const UUIDGeneratorBrowser = () =>
|
||||
|
||||
@ -5,7 +5,7 @@ tags: node,random,intermediate
|
||||
|
||||
Generates a UUID in Node.JS.
|
||||
|
||||
Use `crypto` API to generate a UUID, compliant with [RFC4122](https://www.ietf.org/rfc/rfc4122.txt) version 4.
|
||||
- Use `crypto` API to generate a UUID, compliant with [RFC4122](https://www.ietf.org/rfc/rfc4122.txt) version 4.
|
||||
|
||||
```js
|
||||
const crypto = require('crypto');
|
||||
|
||||
@ -5,7 +5,7 @@ tags: math,array,beginner
|
||||
|
||||
Returns an array of partial sums.
|
||||
|
||||
Use `Array.prototype.reduce()`, `Array.prototype.slice(-1)` and the unary `+` operator to add each value to the unary array containing the previous sum.
|
||||
- Use `Array.prototype.reduce()`, `Array.prototype.slice(-1)` and the unary `+` operator to add each value to the unary array containing the previous sum.
|
||||
|
||||
```js
|
||||
const accumulate = (...nums) => nums.reduce((acc, n) => [...acc, n + +acc.slice(-1)],[]);
|
||||
|
||||
@ -5,8 +5,8 @@ tags: array,function,beginner
|
||||
|
||||
Returns `true` if the provided predicate function returns `true` for all elements in a collection, `false` otherwise.
|
||||
|
||||
Use `Array.prototype.every()` to test if all elements in the collection return `true` based on `fn`.
|
||||
Omit the second argument, `fn`, to use `Boolean` as a default.
|
||||
- Use `Array.prototype.every()` to test if all elements in the collection return `true` based on `fn`.
|
||||
- Omit the second argument, `fn`, to use `Boolean` as a default.
|
||||
|
||||
```js
|
||||
const all = (arr, fn = Boolean) => arr.every(fn);
|
||||
|
||||
@ -5,8 +5,8 @@ tags: array,function,beginner
|
||||
|
||||
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.
|
||||
Elements in the array are compared using the strict comparison operator, which does not account for `NaN` self-inequality.
|
||||
- Use `Array.prototype.every()` to check if all the elements of the array are the same as the first one.
|
||||
- Elements in the array are compared using the strict comparison operator, which does not account for `NaN` self-inequality.
|
||||
|
||||
```js
|
||||
const allEqual = arr => arr.every(val => val === arr[0]);
|
||||
|
||||
@ -5,7 +5,7 @@ tags: math,logic,beginner
|
||||
|
||||
Returns `true` if both arguments are `true`, `false` otherwise.
|
||||
|
||||
Use the logical and (`&&`) operator on the two given values.
|
||||
- Use the logical and (`&&`) operator on the two given values.
|
||||
|
||||
```js
|
||||
const and = (a, b) => a && b;
|
||||
|
||||
@ -5,8 +5,8 @@ tags: array,function,beginner
|
||||
|
||||
Returns `true` if the provided predicate function returns `true` for at least one element in a collection, `false` otherwise.
|
||||
|
||||
Use `Array.prototype.some()` to test if any elements in the collection return `true` based on `fn`.
|
||||
Omit the second argument, `fn`, to use `Boolean` as a default.
|
||||
- Use `Array.prototype.some()` to test if any elements in the collection return `true` based on `fn`.
|
||||
- Omit the second argument, `fn`, to use `Boolean` as a default.
|
||||
|
||||
```js
|
||||
const any = (arr, fn = Boolean) => arr.some(fn);
|
||||
|
||||
@ -5,8 +5,8 @@ tags: array,intermediate
|
||||
|
||||
Returns an array of `n`-tuples of consecutive elements.
|
||||
|
||||
Use `Array.prototype.slice()` and `Array.prototype.map()` to create an array of appropriate length and populate it with `n`-tuples of consecutive elements from `arr`.
|
||||
If `n` is greater than the length of `arr`, return an empty array.
|
||||
- Use `Array.prototype.slice()` and `Array.prototype.map()` to create an array of appropriate length and populate it with `n`-tuples of consecutive elements from `arr`.
|
||||
- If `n` is greater than the length of `arr`, return an empty array.
|
||||
|
||||
```js
|
||||
const aperture = (n, arr) =>
|
||||
|
||||
@ -5,8 +5,8 @@ tags: math,beginner
|
||||
|
||||
Checks if two numbers are approximately equal to each other.
|
||||
|
||||
Use `Math.abs()` to compare the absolute difference of the two values to `epsilon`.
|
||||
Omit the third parameter, `epsilon`, to use a default value of `0.001`.
|
||||
- Use `Math.abs()` to compare the absolute difference of the two values to `epsilon`.
|
||||
- Omit the third parameter, `epsilon`, to use a default value of `0.001`.
|
||||
|
||||
```js
|
||||
const approximatelyEqual = (v1, v2, epsilon = 0.001) => Math.abs(v1 - v2) < epsilon;
|
||||
|
||||
@ -5,9 +5,9 @@ tags: array,string,intermediate
|
||||
|
||||
Converts a 2D array to a comma-separated values (CSV) string.
|
||||
|
||||
Use `Array.prototype.map()` and `Array.prototype.join(delimiter)` to combine individual 1D arrays (rows) into strings.
|
||||
Use `Array.prototype.join('\n')` to combine all rows into a CSV string, separating each row with a newline.
|
||||
Omit the second argument, `delimiter`, to use a default delimiter of `,`.
|
||||
- Use `Array.prototype.map()` and `Array.prototype.join(delimiter)` to combine individual 1D arrays (rows) into strings.
|
||||
- Use `Array.prototype.join('\n')` to combine all rows into a CSV string, separating each row with a newline.
|
||||
- Omit the second argument, `delimiter`, to use a default delimiter of `,`.
|
||||
|
||||
```js
|
||||
const arrayToCSV = (arr, delimiter = ',') =>
|
||||
|
||||
@ -5,7 +5,7 @@ tags: browser,array,intermediate
|
||||
|
||||
Converts the given array elements into `<li>` tags and appends them to the list of the given id.
|
||||
|
||||
Use `Array.prototype.map()` and `document.querySelector()` to create a list of html tags.
|
||||
- Use `Array.prototype.map()` and `document.querySelector()` to create a list of html tags.
|
||||
|
||||
```js
|
||||
const arrayToHtmlList = (arr, listID) =>
|
||||
|
||||
@ -5,7 +5,7 @@ tags: function,intermediate
|
||||
|
||||
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 (`...`).
|
||||
- Call the provided function, `fn`, with up to `n` arguments, using `Array.prototype.slice(0, n)` and the spread operator (`...`).
|
||||
|
||||
```js
|
||||
const ary = (fn, n) => (...args) => fn(...args.slice(0, n));
|
||||
|
||||
@ -5,7 +5,7 @@ tags: node,string,beginner
|
||||
|
||||
Decodes a string of data which has been encoded using base-64 encoding.
|
||||
|
||||
Create a `Buffer` for the given string with base-64 encoding and use `Buffer.toString('binary')` to return the decoded string.
|
||||
- Create a `Buffer` for the given string with base-64 encoding and use `Buffer.toString('binary')` to return the decoded string.
|
||||
|
||||
```js
|
||||
const atob = str => Buffer.from(str, 'base64').toString('binary');
|
||||
|
||||
@ -5,7 +5,7 @@ tags: function,intermediate
|
||||
|
||||
Attempts to invoke a function with the provided arguments, returning either the result or the caught error object.
|
||||
|
||||
Use a `try... catch` block to return either the result of the function or an appropriate error.
|
||||
- Use a `try... catch` block to return either the result of the function or an appropriate error.
|
||||
|
||||
```js
|
||||
const attempt = (fn, ...args) => {
|
||||
|
||||
@ -5,7 +5,7 @@ tags: math,array,beginner
|
||||
|
||||
Returns the average of two or more numbers.
|
||||
|
||||
Use `Array.prototype.reduce()` to add each value to an accumulator, initialized with a value of `0`, divide by the `length` of the array.
|
||||
- Use `Array.prototype.reduce()` to add each value to an accumulator, initialized with a value of `0`, divide by the `length` of the array.
|
||||
|
||||
```js
|
||||
const average = (...nums) => nums.reduce((acc, val) => acc + val, 0) / nums.length;
|
||||
|
||||
@ -5,7 +5,7 @@ tags: math,array,function,intermediate
|
||||
|
||||
Returns the average of an array, after mapping each element to a value using the provided function.
|
||||
|
||||
Use `Array.prototype.map()` to map each element to the value returned by `fn`, `Array.prototype.reduce()` to add each value to an accumulator, initialized with a value of `0`, divide by the `length` of the array.
|
||||
- Use `Array.prototype.map()` to map each element to the value returned by `fn`, `Array.prototype.reduce()` to add each value to an accumulator, initialized with a value of `0`, divide by the `length` of the array.
|
||||
|
||||
```js
|
||||
const averageBy = (arr, fn) =>
|
||||
|
||||
@ -5,7 +5,7 @@ tags: array,intermediate
|
||||
|
||||
Splits values into two groups. If an element in `filter` is truthy, the corresponding element in the collection belongs to the first group; otherwise, it belongs to the second group.
|
||||
|
||||
Use `Array.prototype.reduce()` and `Array.prototype.push()` to add elements to groups, based on `filter`.
|
||||
- Use `Array.prototype.reduce()` and `Array.prototype.push()` to add elements to groups, based on `filter`.
|
||||
|
||||
```js
|
||||
const bifurcate = (arr, filter) =>
|
||||
|
||||
@ -5,7 +5,7 @@ tags: array,function,intermediate
|
||||
|
||||
Splits values into two groups according to a predicate function, which specifies which group an element in the input collection belongs to. If the predicate function returns a truthy value, the collection element belongs to the first group; otherwise, it belongs to the second group.
|
||||
|
||||
Use `Array.prototype.reduce()` and `Array.prototype.push()` to add elements to groups, based on the value returned by `fn` for each element.
|
||||
- Use `Array.prototype.reduce()` and `Array.prototype.push()` to add elements to groups, based on the value returned by `fn` for each element.
|
||||
|
||||
```js
|
||||
const bifurcateBy = (arr, fn) =>
|
||||
|
||||
@ -5,7 +5,7 @@ tags: function,beginner
|
||||
|
||||
Creates a function that accepts up to two arguments, ignoring any additional arguments.
|
||||
|
||||
Call the provided function, `fn`, with the first two arguments given.
|
||||
- Call the provided function, `fn`, with the first two arguments given.
|
||||
|
||||
```js
|
||||
const binary = fn => (a, b) => fn(a, b);
|
||||
|
||||
@ -5,8 +5,8 @@ tags: function,object,intermediate
|
||||
|
||||
Creates a function that invokes `fn` with a given context, optionally adding any additional supplied parameters to the beginning of the arguments.
|
||||
|
||||
Return a `function` that uses `Function.prototype.apply()` to apply the given `context` to `fn`.
|
||||
Use `Array.prototype.concat()` to prepend any additional supplied parameters to the arguments.
|
||||
- Return a `function` that uses `Function.prototype.apply()` to apply the given `context` to `fn`.
|
||||
- Use `Array.prototype.concat()` to prepend any additional supplied parameters to the arguments.
|
||||
|
||||
```js
|
||||
const bind = (fn, context, ...boundArgs) => (...args) => fn.apply(context, [...boundArgs, ...args]);
|
||||
|
||||
@ -5,7 +5,7 @@ tags: object,function,intermediate
|
||||
|
||||
Binds methods of an object to the object itself, overwriting the existing method.
|
||||
|
||||
Use `Array.prototype.forEach()` to return a `function` that uses `Function.prototype.apply()` to apply the given context (`obj`) to `fn` for each function specified.
|
||||
- Use `Array.prototype.forEach()` to return a `function` that uses `Function.prototype.apply()` to apply the given context (`obj`) to `fn` for each function specified.
|
||||
|
||||
```js
|
||||
const bindAll = (obj, ...fns) =>
|
||||
|
||||
@ -5,8 +5,8 @@ tags: function,object,intermediate
|
||||
|
||||
Creates a function that invokes the method at a given key of an object, optionally adding any additional supplied parameters to the beginning of the arguments.
|
||||
|
||||
Return a `function` that uses `Function.prototype.apply()` to bind `context[fn]` to `context`.
|
||||
Use the spread operator (`...`) to prepend any additional supplied parameters to the arguments.
|
||||
- Return a `function` that uses `Function.prototype.apply()` to bind `context[fn]` to `context`.
|
||||
- Use the spread operator (`...`) to prepend any additional supplied parameters to the arguments.
|
||||
|
||||
```js
|
||||
const bindKey = (context, fn, ...boundArgs) => (...args) =>
|
||||
|
||||
@ -5,11 +5,11 @@ tags: math,intermediate
|
||||
|
||||
Evaluates the binomial coefficient of two integers `n` and `k`.
|
||||
|
||||
Use `Number.isNaN()` to check if any of the two values is `NaN`.
|
||||
Check if `k` is less than `0`, greater than or equal to `n`, equal to `1` or `n - 1` and return the appropriate result.
|
||||
Check if `n - k` is less than `k` and switch their values accordingly.
|
||||
Loop from `2` through `k` and calculate the binomial coefficient.
|
||||
Use `Math.round()` to account for rounding errors in the calculation.
|
||||
- Use `Number.isNaN()` to check if any of the two values is `NaN`.
|
||||
- Check if `k` is less than `0`, greater than or equal to `n`, equal to `1` or `n - 1` and return the appropriate result.
|
||||
- Check if `n - k` is less than `k` and switch their values accordingly.
|
||||
- Loop from `2` through `k` and calculate the binomial coefficient.
|
||||
- Use `Math.round()` to account for rounding errors in the calculation.
|
||||
|
||||
```js
|
||||
const binomialCoefficient = (n, k) => {
|
||||
|
||||
@ -5,7 +5,7 @@ tags: function,logic,beginner
|
||||
|
||||
Returns `true` if both functions return `true` for a given set of arguments, `false` otherwise.
|
||||
|
||||
Use the logical and (`&&`) operator on the result of calling the two functions with the supplied `args`.
|
||||
- Use the logical and (`&&`) operator on the result of calling the two functions with the supplied `args`.
|
||||
|
||||
```js
|
||||
const both = (f, g) => (...args) => f(...args) && g(...args);
|
||||
|
||||
@ -5,7 +5,7 @@ tags: browser,intermediate
|
||||
|
||||
Returns `true` if the bottom of the page is visible, `false` otherwise.
|
||||
|
||||
Use `scrollY`, `scrollHeight` and `clientHeight` to determine if the bottom of the page is visible.
|
||||
- Use `scrollY`, `scrollHeight` and `clientHeight` to determine if the bottom of the page is visible.
|
||||
|
||||
```js
|
||||
const bottomVisible = () =>
|
||||
|
||||
@ -5,7 +5,7 @@ tags: node,string,beginner
|
||||
|
||||
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 `Buffer` for the given string with binary encoding and use `Buffer.toString('base64')` to return the encoded string.
|
||||
- Create a `Buffer` for the given string with binary encoding and use `Buffer.toString('base64')` to return the encoded string.
|
||||
|
||||
```js
|
||||
const btoa = str => Buffer.from(str, 'binary').toString('base64');
|
||||
|
||||
@ -5,7 +5,7 @@ tags: string,beginner
|
||||
|
||||
Returns the length of a string in bytes.
|
||||
|
||||
Convert a given string to a [`Blob` Object](https://developer.mozilla.org/en-US/docs/Web/API/Blob) and find its `size`.
|
||||
- Convert a given string to a [`Blob` Object](https://developer.mozilla.org/en-US/docs/Web/API/Blob) and find its `size`.
|
||||
|
||||
```js
|
||||
const byteSize = str => new Blob([str]).size;
|
||||
|
||||
@ -5,7 +5,7 @@ tags: function,intermediate
|
||||
|
||||
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.
|
||||
- Use a closure to call a stored key with stored arguments.
|
||||
|
||||
```js
|
||||
const call = (key, ...args) => context => context[key](...args);
|
||||
|
||||
@ -5,8 +5,8 @@ tags: string,array,intermediate
|
||||
|
||||
Capitalizes the first letter of a string.
|
||||
|
||||
Use array destructuring and `String.prototype.toUpperCase()` to capitalize first letter, `...rest` to get array of characters after first letter and then `Array.prototype.join('')` to make it a string again.
|
||||
Omit the `lowerRest` parameter to keep the rest of the string intact, or set it to `true` to convert to lowercase.
|
||||
- Use array destructuring and `String.prototype.toUpperCase()` to capitalize first letter, `...rest` to get array of characters after first letter and then `Array.prototype.join('')` to make it a string again.
|
||||
- Omit the `lowerRest` parameter to keep the rest of the string intact, or set it to `true` to convert to lowercase.
|
||||
|
||||
```js
|
||||
const capitalize = ([first, ...rest], lowerRest = false) =>
|
||||
|
||||
@ -5,7 +5,7 @@ tags: string,regexp,intermediate
|
||||
|
||||
Capitalizes the first letter of every word in a string.
|
||||
|
||||
Use `String.prototype.replace()` to match the first character of each word and `String.prototype.toUpperCase()` to capitalize it.
|
||||
- Use `String.prototype.replace()` to match the first character of each word and `String.prototype.toUpperCase()` to capitalize it.
|
||||
|
||||
```js
|
||||
const capitalizeEveryWord = str => str.replace(/\b[a-z]/g, char => char.toUpperCase());
|
||||
|
||||
@ -5,7 +5,7 @@ tags: type,array,beginner
|
||||
|
||||
Casts the provided value as an array if it's not one.
|
||||
|
||||
Use `Array.prototype.isArray()` to determine if `val` is an array and return it as-is or encapsulated in an array accordingly.
|
||||
- Use `Array.prototype.isArray()` to determine if `val` is an array and return it as-is or encapsulated in an array accordingly.
|
||||
|
||||
```js
|
||||
const castArray = val => (Array.isArray(val) ? val : [val]);
|
||||
|
||||
@ -5,7 +5,7 @@ tags: math,beginner
|
||||
|
||||
Converts Celsius to Fahrenheit.
|
||||
|
||||
Follows the conversion formula `F = 1.8C + 32`.
|
||||
- Follows the conversion formula `F = 1.8C + 32`.
|
||||
|
||||
```js
|
||||
const celsiusToFahrenheit = degrees => 1.8 * degrees + 32;
|
||||
|
||||
@ -5,7 +5,7 @@ tags: function,intermediate
|
||||
|
||||
Chains asynchronous functions.
|
||||
|
||||
Loop through an array of functions containing asynchronous events, calling `next` when each asynchronous event has completed.
|
||||
- Loop through an array of functions containing asynchronous events, calling `next` when each asynchronous event has completed.
|
||||
|
||||
```js
|
||||
const chainAsync = fns => {
|
||||
|
||||
@ -5,7 +5,7 @@ tags: function,object,beginner
|
||||
|
||||
Given a `predicate` function and a `prop` string, this curried function will then take an `object` to inspect by calling the property and passing it to the predicate.
|
||||
|
||||
Summon `prop` on `obj`, pass it to a provided `predicate` function and return a masked boolean.
|
||||
- Summon `prop` on `obj`, pass it to a provided `predicate` function and return a masked boolean.
|
||||
|
||||
```js
|
||||
const checkProp = (predicate, prop) => obj => !!predicate(obj[prop]);
|
||||
|
||||
@ -5,9 +5,9 @@ tags: array,intermediate
|
||||
|
||||
Chunks an array into smaller arrays of a specified size.
|
||||
|
||||
Use `Array.from()` to create a new array, that fits the number of chunks that will be produced.
|
||||
Use `Array.prototype.slice()` to map each element of the new array to a chunk the length of `size`.
|
||||
If the original array can't be split evenly, the final chunk will contain the remaining elements.
|
||||
- Use `Array.from()` to create a new array, that fits the number of chunks that will be produced.
|
||||
- Use `Array.prototype.slice()` to map each element of the new array to a chunk the length of `size`.
|
||||
- If the original array can't be split evenly, the final chunk will contain the remaining elements.
|
||||
|
||||
```js
|
||||
const chunk = (arr, size) =>
|
||||
|
||||
@ -5,10 +5,10 @@ tags: array,intermediate
|
||||
|
||||
Chunks an array into `n` smaller arrays.
|
||||
|
||||
Use `Math.ceil()` and `Array.prototype.length` to get the size of each chunk.
|
||||
Use `Array.from()` to create a new array of size `n`.
|
||||
Use `Array.prototype.slice()` to map each element of the new array to a chunk the length of `size`.
|
||||
If the original array can't be split evenly, the final chunk will contain the remaining elements.
|
||||
- Use `Math.ceil()` and `Array.prototype.length` to get the size of each chunk.
|
||||
- Use `Array.from()` to create a new array of size `n`.
|
||||
- Use `Array.prototype.slice()` to map each element of the new array to a chunk the length of `size`.
|
||||
- If the original array can't be split evenly, the final chunk will contain the remaining elements.
|
||||
|
||||
```js
|
||||
const chunkIntoN = (arr, n) => {
|
||||
|
||||
@ -5,8 +5,8 @@ tags: math,beginner
|
||||
|
||||
Clamps `num` within the inclusive range specified by the boundary values `a` and `b`.
|
||||
|
||||
If `num` falls within the range, return `num`.
|
||||
Otherwise, return the nearest number in the range.
|
||||
- If `num` falls within the range, return `num`.
|
||||
- Otherwise, return the nearest number in the range.
|
||||
|
||||
```js
|
||||
const clampNumber = (num, a, b) => Math.max(Math.min(num, Math.max(a, b)), Math.min(a, b));
|
||||
|
||||
@ -5,7 +5,7 @@ tags: type,string,regexp,intermediate
|
||||
|
||||
Clones a regular expression.
|
||||
|
||||
Use `new RegExp()`, `RegExp.source` and `RegExp.flags` to clone the given regular expression.
|
||||
- Use `new RegExp()`, `RegExp.source` and `RegExp.flags` to clone the given regular expression.
|
||||
|
||||
```js
|
||||
const cloneRegExp = regExp => new RegExp(regExp.source, regExp.flags);
|
||||
|
||||
@ -5,7 +5,7 @@ tags: type,beginner
|
||||
|
||||
Returns the first defined, non-null argument.
|
||||
|
||||
Use `Array.prototype.find()` and `Array.prototype.includes()` to find the first value that is not equal to `undefined` or `null`.
|
||||
- Use `Array.prototype.find()` and `Array.prototype.includes()` to find the first value that is not equal to `undefined` or `null`.
|
||||
|
||||
```js
|
||||
const coalesce = (...args) => args.find(v => ![undefined, null].includes(v));
|
||||
|
||||
@ -5,7 +5,7 @@ tags: type,intermediate
|
||||
|
||||
Returns a customized coalesce function that returns the first argument that returns `true` from the provided argument validation function.
|
||||
|
||||
Use `Array.prototype.find()` to return the first argument that returns `true` from the provided argument validation function.
|
||||
- Use `Array.prototype.find()` to return the first argument that returns `true` from the provided argument validation function.
|
||||
|
||||
```js
|
||||
const coalesceFactory = valid => (...args) => args.find(valid);
|
||||
|
||||
@ -5,7 +5,7 @@ tags: function,array,intermediate
|
||||
|
||||
Changes a function that accepts an array into a variadic function.
|
||||
|
||||
Given a function, return a closure that collects all inputs into an array-accepting function.
|
||||
- Given a function, return a closure that collects all inputs into an array-accepting function.
|
||||
|
||||
```js
|
||||
const collectInto = fn => (...args) => fn(args);
|
||||
|
||||
@ -5,8 +5,8 @@ tags: node,string,intermediate
|
||||
|
||||
Add special characters to text to print in color in the console (combined with `console.log()`).
|
||||
|
||||
Use template literals and special characters to add the appropriate color code to the string output.
|
||||
For background colors, add a special character that resets the background color at the end of the string.
|
||||
- Use template literals and special characters to add the appropriate color code to the string output.
|
||||
- For background colors, add a special character that resets the background color at the end of the string.
|
||||
|
||||
```js
|
||||
const colorize = (...args) => ({
|
||||
|
||||
@ -5,7 +5,7 @@ tags: array,beginner
|
||||
|
||||
Removes falsy values from an array.
|
||||
|
||||
Use `Array.prototype.filter()` to filter out falsy values (`false`, `null`, `0`, `""`, `undefined`, and `NaN`).
|
||||
- Use `Array.prototype.filter()` to filter out falsy values (`false`, `null`, `0`, `""`, `undefined`, and `NaN`).
|
||||
|
||||
```js
|
||||
const compact = arr => arr.filter(Boolean);
|
||||
|
||||
@ -5,7 +5,7 @@ tags: string,regexp,beginner
|
||||
|
||||
Returns a string with whitespaces compacted.
|
||||
|
||||
Use `String.prototype.replace()` with a regular expression to replace all occurrences of 2 or more whitespace characters with a single space.
|
||||
- Use `String.prototype.replace()` with a regular expression to replace all occurrences of 2 or more whitespace characters with a single space.
|
||||
|
||||
```js
|
||||
const compactWhitespace = str => str.replace(/\s{2,}/g, ' ');
|
||||
|
||||
@ -5,7 +5,7 @@ tags: function,logic,beginner
|
||||
|
||||
Returns a function that is the logical complement of the given function, `fn`.
|
||||
|
||||
Use the logical not (`!`) operator on the result of calling `fn` with any supplied `args`.
|
||||
- Use the logical not (`!`) operator on the result of calling `fn` with any supplied `args`.
|
||||
|
||||
```js
|
||||
const complement = fn => (...args) => !fn(...args);
|
||||
|
||||
@ -5,8 +5,8 @@ tags: function,intermediate
|
||||
|
||||
Performs right-to-left function composition.
|
||||
|
||||
Use `Array.prototype.reduce()` to perform right-to-left function composition.
|
||||
The last (rightmost) function can accept one or more arguments; the remaining functions must be unary.
|
||||
- Use `Array.prototype.reduce()` to perform right-to-left function composition.
|
||||
- The last (rightmost) function can accept one or more arguments; the remaining functions must be unary.
|
||||
|
||||
```js
|
||||
const compose = (...fns) => fns.reduce((f, g) => (...args) => f(g(...args)));
|
||||
|
||||
@ -5,8 +5,8 @@ tags: function,intermediate
|
||||
|
||||
Performs left-to-right function composition.
|
||||
|
||||
Use `Array.prototype.reduce()` to perform left-to-right function composition.
|
||||
The first (leftmost) function can accept one or more arguments; the remaining functions must be unary.
|
||||
- Use `Array.prototype.reduce()` to perform left-to-right function composition.
|
||||
- The first (leftmost) function can accept one or more arguments; the remaining functions must be unary.
|
||||
|
||||
```js
|
||||
const composeRight = (...fns) => fns.reduce((f, g) => (...args) => g(f(...args)));
|
||||
|
||||
@ -5,7 +5,7 @@ tags: string,regexp,beginner
|
||||
|
||||
Returns `true` if the given string contains any whitespace characters, `false` otherwise.
|
||||
|
||||
Use `RegExp.prototype.test()` with an appropriate regular expression to check if the given string contains any whitespace characters.
|
||||
- Use `RegExp.prototype.test()` with an appropriate regular expression to check if the given string contains any whitespace characters.
|
||||
|
||||
```js
|
||||
const containsWhitespace = str => /\s/.test(str);
|
||||
|
||||
@ -5,8 +5,8 @@ tags: function,intermediate
|
||||
|
||||
Accepts a converging function and a list of branching functions and returns a function that applies each branching function to the arguments and the results of the branching functions are passed as arguments to the converging function.
|
||||
|
||||
Use `Array.prototype.map()` and `Function.prototype.apply()` to apply each function to the given arguments.
|
||||
Use the spread operator (`...`) to call `coverger` with the results of all other functions.
|
||||
- Use `Array.prototype.map()` and `Function.prototype.apply()` to apply each function to the given arguments.
|
||||
- Use the spread operator (`...`) to call `coverger` with the results of all other functions.
|
||||
|
||||
```js
|
||||
const converge = (converger, fns) => (...args) => converger(...fns.map(fn => fn.apply(null, args)));
|
||||
|
||||
@ -6,13 +6,12 @@ tags: browser,string,advanced
|
||||
Copy a string to the clipboard.
|
||||
Only works as a result of user action (i.e. inside a `click` event listener).
|
||||
|
||||
⚠️ **NOTICE:** The same functionality can be easily implemented by using the new asynchronous Clipboard API, which is still experimental but should be used in the future instead of this snippet. Find out more about it [here](https://github.com/w3c/clipboard-apis/blob/master/explainer.adoc#writing-to-the-clipboard).
|
||||
|
||||
Create a new `<textarea>` element, fill it with the supplied data and add it to the HTML document.
|
||||
Use `Selection.getRangeAt()`to store the selected range (if any).
|
||||
Use `document.execCommand('copy')` to copy to the clipboard.
|
||||
Remove the `<textarea>` element from the HTML document.
|
||||
Finally, use `Selection().addRange()` to recover the original selected range (if any).
|
||||
- Create a new `<textarea>` element, fill it with the supplied data and add it to the HTML document.
|
||||
- Use `Selection.getRangeAt()`to store the selected range (if any).
|
||||
- Use `document.execCommand('copy')` to copy to the clipboard.
|
||||
- Remove the `<textarea>` element from the HTML document.
|
||||
- Finally, use `Selection().addRange()` to recover the original selected range (if any).
|
||||
- ⚠️ **NOTICE:** The same functionality can be easily implemented by using the new asynchronous Clipboard API, which is still experimental but should be used in the future instead of this snippet. Find out more about it [here](https://github.com/w3c/clipboard-apis/blob/master/explainer.adoc#writing-to-the-clipboard).
|
||||
|
||||
```js
|
||||
const copyToClipboard = str => {
|
||||
|
||||
@ -5,8 +5,8 @@ tags: array,object,intermediate
|
||||
|
||||
Groups the elements of an array based on the given function and returns the count of elements in each group.
|
||||
|
||||
Use `Array.prototype.map()` to map the values of an array to a function or property name.
|
||||
Use `Array.prototype.reduce()` to create an object, where the keys are produced from the mapped results.
|
||||
- Use `Array.prototype.map()` to map the values of an array to a function or property name.
|
||||
- Use `Array.prototype.reduce()` to create an object, where the keys are produced from the mapped results.
|
||||
|
||||
```js
|
||||
const countBy = (arr, fn) =>
|
||||
|
||||
@ -5,7 +5,7 @@ tags: array,intermediate
|
||||
|
||||
Counts the occurrences of a value in an array.
|
||||
|
||||
Use `Array.prototype.reduce()` to increment a counter each time you encounter the specific value inside the array.
|
||||
- Use `Array.prototype.reduce()` to increment a counter each time you encounter the specific value inside the array.
|
||||
|
||||
```js
|
||||
const countOccurrences = (arr, val) => arr.reduce((a, v) => (v === val ? a + 1 : a), 0);
|
||||
|
||||
@ -5,11 +5,11 @@ tags: browser,advanced
|
||||
|
||||
Creates a counter with the specified range, step and duration for the specified selector.
|
||||
|
||||
Check if `step` has the proper sign and change it accordingly.
|
||||
Use `setInterval()` in combination with `Math.abs()` and `Math.floor()` to calculate the time between each new text draw.
|
||||
Use `document.querySelector().innerHTML` to update the value of the selected element.
|
||||
Omit the fourth parameter, `step`, to use a default step of `1`.
|
||||
Omit the fifth parameter, `duration`, to use a default duration of `2000`ms.
|
||||
- Check if `step` has the proper sign and change it accordingly.
|
||||
- Use `setInterval()` in combination with `Math.abs()` and `Math.floor()` to calculate the time between each new text draw.
|
||||
- Use `document.querySelector().innerHTML` to update the value of the selected element.
|
||||
- Omit the fourth parameter, `step`, to use a default step of `1`.
|
||||
- Omit the fifth parameter, `duration`, to use a default duration of `2000`ms.
|
||||
|
||||
```js
|
||||
const counter = (selector, start, end, step = 1, duration = 2000) => {
|
||||
|
||||
@ -5,7 +5,7 @@ tags: node,beginner
|
||||
|
||||
Creates a directory, if it does not exist.
|
||||
|
||||
Use `fs.existsSync()` to check if the directory exists, `fs.mkdirSync()` to create it.
|
||||
- Use `fs.existsSync()` to check if the directory exists, `fs.mkdirSync()` to create it.
|
||||
|
||||
```js
|
||||
const fs = require('fs');
|
||||
|
||||
@ -6,9 +6,9 @@ tags: browser,beginner
|
||||
Creates an element from a string (without appending it to the document).
|
||||
If the given string contains multiple elements, only the first one will be returned.
|
||||
|
||||
Use `document.createElement()` to create a new element.
|
||||
Set its `innerHTML` to the string supplied as the argument.
|
||||
Use `ParentNode.firstElementChild` to return the element version of the string.
|
||||
- Use `document.createElement()` to create a new element.
|
||||
- Set its `innerHTML` to the string supplied as the argument.
|
||||
- Use `ParentNode.firstElementChild` to return the element version of the string.
|
||||
|
||||
```js
|
||||
const createElement = str => {
|
||||
|
||||
@ -5,11 +5,11 @@ tags: browser,event,advanced
|
||||
|
||||
Creates a pub/sub ([publish–subscribe](https://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern)) event hub with `emit`, `on`, and `off` methods.
|
||||
|
||||
Use `Object.create(null)` to create an empty `hub` object that does not inherit properties from `Object.prototype`.
|
||||
For `emit`, resolve the array of handlers based on the `event` argument and then run each one with `Array.prototype.forEach()` by passing in the data as an argument.
|
||||
For `on`, create an array for the event if it does not yet exist, then use `Array.prototype.push()` to add the handler
|
||||
to the array.
|
||||
For `off`, use `Array.prototype.findIndex()` to find the index of the handler in the event array and remove it using `Array.prototype.splice()`.
|
||||
- Use `Object.create(null)` to create an empty `hub` object that does not inherit properties from `Object.prototype`.
|
||||
- For `emit`, resolve the array of handlers based on the `event` argument and then run each one with `Array.prototype.forEach()` by passing in the data as an argument.
|
||||
- For `on`, create an array for the event if it does not yet exist, then use `Array.prototype.push()` to add the handler
|
||||
- to the array.
|
||||
- For `off`, use `Array.prototype.findIndex()` to find the index of the handler in the event array and remove it using `Array.prototype.splice()`.
|
||||
|
||||
```js
|
||||
const createEventHub = () => ({
|
||||
|
||||
@ -5,7 +5,7 @@ tags: browser,url,beginner
|
||||
|
||||
Returns the current URL.
|
||||
|
||||
Use `window.location.href` to get the current URL.
|
||||
- Use `window.location.href` to get the current URL.
|
||||
|
||||
```js
|
||||
const currentURL = () => window.location.href;
|
||||
|
||||
@ -5,10 +5,10 @@ tags: function,recursion,intermediate
|
||||
|
||||
Curries a function.
|
||||
|
||||
Use recursion.
|
||||
If the number of provided arguments (`args`) is sufficient, call the passed function `fn`.
|
||||
Otherwise, return a curried function `fn` that expects the rest of the arguments.
|
||||
If you want to curry a function that accepts a variable number of arguments (a variadic function, e.g. `Math.min()`), you can optionally pass the number of arguments to the second parameter `arity`.
|
||||
- Use recursion.
|
||||
- If the number of provided arguments (`args`) is sufficient, call the passed function `fn`.
|
||||
- Otherwise, return a curried function `fn` that expects the rest of the arguments.
|
||||
- If you want to curry a function that accepts a variable number of arguments (a variadic function, e.g. `Math.min()`), you can optionally pass the number of arguments to the second parameter `arity`.
|
||||
|
||||
```js
|
||||
const curry = (fn, arity = fn.length, ...args) =>
|
||||
|
||||
@ -5,8 +5,8 @@ tags: date,beginner
|
||||
|
||||
Gets the day of the year from a `Date` object.
|
||||
|
||||
Use `new Date()` and `Date.prototype.getFullYear()` to get the first day of the year as a `Date` object, subtract it from the provided `date` and divide with the milliseconds in each day to get the result.
|
||||
Use `Math.floor()` to appropriately round the resulting day count to an integer.
|
||||
- Use `new Date()` and `Date.prototype.getFullYear()` to get the first day of the year as a `Date` object, subtract it from the provided `date` and divide with the milliseconds in each day to get the result.
|
||||
- Use `Math.floor()` to appropriately round the resulting day count to an integer.
|
||||
|
||||
```js
|
||||
const dayOfYear = date =>
|
||||
|
||||
@ -5,8 +5,9 @@ tags: function,intermediate
|
||||
|
||||
Creates a debounced function that delays invoking the provided function until at least `ms` milliseconds have elapsed since the last time it was invoked.
|
||||
|
||||
Each time the debounced function is invoked, clear the current pending timeout with `clearTimeout()` and use `setTimeout()` to create a new timeout that delays invoking the function until at least `ms` milliseconds has elapsed. Use `Function.prototype.apply()` to apply the `this` context to the function and provide the necessary arguments.
|
||||
Omit the second argument, `ms`, to set the timeout at a default of 0 ms.
|
||||
- Each time the debounced function is invoked, clear the current pending timeout with `clearTimeout()` and use `setTimeout()` to create a new timeout that delays invoking the function until at least `ms` milliseconds has elapsed.
|
||||
- Use `Function.prototype.apply()` to apply the `this` context to the function and provide the necessary arguments.
|
||||
- Omit the second argument, `ms`, to set the timeout at a default of 0 ms.
|
||||
|
||||
```js
|
||||
const debounce = (fn, ms = 0) => {
|
||||
|
||||
@ -5,8 +5,8 @@ tags: string,array,intermediate
|
||||
|
||||
Decapitalizes the first letter of a string.
|
||||
|
||||
Use array destructuring and `String.toLowerCase()` to decapitalize first letter, `...rest` to get array of characters after first letter and then `Array.prototype.join('')` to make it a string again.
|
||||
Omit the `upperRest` parameter to keep the rest of the string intact, or set it to `true` to convert to uppercase.
|
||||
- Use array destructuring and `String.toLowerCase()` to decapitalize first letter, `...rest` to get array of characters after first letter and then `Array.prototype.join('')` to make it a string again.
|
||||
- Omit the `upperRest` parameter to keep the rest of the string intact, or set it to `true` to convert to uppercase.
|
||||
|
||||
```js
|
||||
const decapitalize = ([first, ...rest], upperRest = false) =>
|
||||
|
||||
@ -6,11 +6,11 @@ tags: object,recursion,intermediate
|
||||
Creates a deep clone of an object.
|
||||
Clones primitives, arrays and objects, excluding class instances.
|
||||
|
||||
Use recursion.
|
||||
Check if the passed object is `null` and, if so, return `null`.
|
||||
Use `Object.assign()` and an empty object (`{}`) to create a shallow clone of the original.
|
||||
Use `Object.keys()` and `Array.prototype.forEach()` to determine which key-value pairs need to be deep cloned.
|
||||
If the object is an `Array`, set the `clone`'s `length` to that of the original and use `Array.from(clone)` to create a clone.
|
||||
- Use recursion.
|
||||
- Check if the passed object is `null` and, if so, return `null`.
|
||||
- Use `Object.assign()` and an empty object (`{}`) to create a shallow clone of the original.
|
||||
- Use `Object.keys()` and `Array.prototype.forEach()` to determine which key-value pairs need to be deep cloned.
|
||||
- If the object is an `Array`, set the `clone`'s `length` to that of the original and use `Array.from(clone)` to create a clone.
|
||||
|
||||
```js
|
||||
const deepClone = obj => {
|
||||
|
||||
@ -5,9 +5,9 @@ tags: array,recursion,intermediate
|
||||
|
||||
Deep flattens an array.
|
||||
|
||||
Use recursion.
|
||||
Use `Array.prototype.concat()` with an empty array (`[]`) and the spread operator (`...`) to flatten an array.
|
||||
Recursively flatten each element that is an array.
|
||||
- Use recursion.
|
||||
- Use `Array.prototype.concat()` with an empty array (`[]`) and the spread operator (`...`) to flatten an array.
|
||||
- Recursively flatten each element that is an array.
|
||||
|
||||
```js
|
||||
const deepFlatten = arr => [].concat(...arr.map(v => (Array.isArray(v) ? deepFlatten(v) : v)));
|
||||
|
||||
@ -5,9 +5,9 @@ tags: object,recursion,intermediate
|
||||
|
||||
Deep freezes an object.
|
||||
|
||||
Use `Object.keys()` to get all the properties of the passed object, `Array.prototype.forEach()` to iterate over them.
|
||||
Call `Object.freeze(obj)` recursively on all properties, applying `deepFreeze()` as necessary.
|
||||
Finally, use `Object.freeze()` to freeze the given object.
|
||||
- Use `Object.keys()` to get all the properties of the passed object, `Array.prototype.forEach()` to iterate over them.
|
||||
- Call `Object.freeze(obj)` recursively on all properties, applying `deepFreeze()` as necessary.
|
||||
- Finally, use `Object.freeze()` to freeze the given object.
|
||||
|
||||
```js
|
||||
const deepFreeze = obj => {
|
||||
|
||||
@ -5,9 +5,9 @@ tags: object,intermediate
|
||||
|
||||
Returns the target value in a nested JSON object, based on the `keys` array.
|
||||
|
||||
Compare the keys you want in the nested JSON object as an `Array`.
|
||||
Use `Array.prototype.reduce()` to get value from nested JSON object one by one.
|
||||
If the key exists in object, return target value, otherwise, return `null`.
|
||||
- Compare the keys you want in the nested JSON object as an `Array`.
|
||||
- Use `Array.prototype.reduce()` to get value from nested JSON object one by one.
|
||||
- If the key exists in object, return target value, otherwise, return `null`.
|
||||
|
||||
```js
|
||||
const deepGet = (obj, keys) =>
|
||||
|
||||
@ -5,9 +5,9 @@ tags: object,recursion,advanced
|
||||
|
||||
Deep maps an object's keys.
|
||||
|
||||
Creates an object with the same values as the provided object and keys generated by running the provided function for each key.
|
||||
Use `Object.keys(obj)` to iterate over the object's keys.
|
||||
Use `Array.prototype.reduce()` to create a new object with the same values and mapped keys using `fn`.
|
||||
- Creates an object with the same values as the provided object and keys generated by running the provided function for each key.
|
||||
- Use `Object.keys(obj)` to iterate over the object's keys.
|
||||
- Use `Array.prototype.reduce()` to create a new object with the same values and mapped keys using `fn`.
|
||||
|
||||
```js
|
||||
const deepMapKeys = (obj, fn) =>
|
||||
|
||||
@ -5,7 +5,7 @@ tags: object,intermediate
|
||||
|
||||
Assigns default values for all properties in an object that are `undefined`.
|
||||
|
||||
Use `Object.assign()` to create a new empty object and copy the original one to maintain key order, use `Array.prototype.reverse()` and the spread operator `...` to combine the default values from left to right, finally use `obj` again to overwrite properties that originally had a value.
|
||||
- Use `Object.assign()` to create a new empty object and copy the original one to maintain key order, use `Array.prototype.reverse()` and the spread operator `...` to combine the default values from left to right, finally use `obj` again to overwrite properties that originally had a value.
|
||||
|
||||
```js
|
||||
const defaults = (obj, ...defs) => Object.assign({}, obj, ...defs.reverse(), obj);
|
||||
|
||||
@ -5,7 +5,8 @@ tags: function,intermediate
|
||||
|
||||
Defers invoking a function until the current call stack has cleared.
|
||||
|
||||
Use `setTimeout()` with a timeout of 1ms to add a new event to the browser event queue and allow the rendering engine to complete its work. Use the spread (`...`) operator to supply the function with an arbitrary number of arguments.
|
||||
- Use `setTimeout()` with a timeout of 1ms to add a new event to the browser event queue and allow the rendering engine to complete its work.
|
||||
- Use the spread (`...`) operator to supply the function with an arbitrary number of arguments.
|
||||
|
||||
```js
|
||||
const defer = (fn, ...args) => setTimeout(fn, 1, ...args);
|
||||
|
||||
@ -5,7 +5,7 @@ tags: math,beginner
|
||||
|
||||
Converts an angle from degrees to radians.
|
||||
|
||||
Use `Math.PI` and the degree to radian formula to convert the angle from degrees to radians.
|
||||
- Use `Math.PI` and the degree to radian formula to convert the angle from degrees to radians.
|
||||
|
||||
```js
|
||||
const degreesToRads = deg => (deg * Math.PI) / 180.0;
|
||||
|
||||
@ -5,8 +5,8 @@ tags: function,intermediate
|
||||
|
||||
Invokes the provided function after `wait` milliseconds.
|
||||
|
||||
Use `setTimeout()` to delay execution of `fn`.
|
||||
Use the spread (`...`) operator to supply the function with an arbitrary number of arguments.
|
||||
- Use `setTimeout()` to delay execution of `fn`.
|
||||
- Use the spread (`...`) operator to supply the function with an arbitrary number of arguments.
|
||||
|
||||
```js
|
||||
const delay = (fn, wait, ...args) => setTimeout(fn, wait, ...args);
|
||||
|
||||
@ -5,7 +5,7 @@ tags: browser,intermediate
|
||||
|
||||
Detects whether the website is being opened in a mobile device or a desktop/laptop.
|
||||
|
||||
Use a regular expression to test the `navigator.userAgent` property to figure out if the device is a mobile device or a desktop/laptop.
|
||||
- Use a regular expression to test the `navigator.userAgent` property to figure out if the device is a mobile device or a desktop/laptop.
|
||||
|
||||
```js
|
||||
const detectDeviceType = () =>
|
||||
|
||||
@ -5,7 +5,7 @@ tags: array,math,beginner
|
||||
|
||||
Returns the difference between two arrays.
|
||||
|
||||
Create a `Set` from `b`, then use `Array.prototype.filter()` on `a` to only keep values not contained in `b`.
|
||||
- Create a `Set` from `b`, then use `Array.prototype.filter()` on `a` to only keep values not contained in `b`.
|
||||
|
||||
```js
|
||||
const difference = (a, b) => {
|
||||
|
||||
@ -5,7 +5,7 @@ tags: array,function,intermediate
|
||||
|
||||
Returns the difference between two arrays, after applying the provided function to each array element of both.
|
||||
|
||||
Create a `Set` by applying `fn` to each element in `b`, then use `Array.prototype.map()` to apply `fn` to each element in `a`, then `Array.prototype.filter()`
|
||||
- Create a `Set` by applying `fn` to each element in `b`, then use `Array.prototype.map()` to apply `fn` to each element in `a`, then `Array.prototype.filter()`
|
||||
|
||||
```js
|
||||
const differenceBy = (a, b, fn) => {
|
||||
|
||||
@ -5,7 +5,7 @@ tags: array,function,intermediate
|
||||
|
||||
Filters out all values from an array for which the comparator function does not return `true`.
|
||||
|
||||
Use `Array.prototype.filter()` and `Array.prototype.findIndex()` to find the appropriate values.
|
||||
- Use `Array.prototype.filter()` and `Array.prototype.findIndex()` to find the appropriate values.
|
||||
|
||||
```js
|
||||
const differenceWith = (arr, val, comp) => arr.filter(a => val.findIndex(b => comp(a, b)) === -1);
|
||||
|
||||
@ -5,8 +5,8 @@ tags: object,recursion,intermediate
|
||||
|
||||
Returns the target value in a nested JSON object, based on the given key.
|
||||
|
||||
Use the `in` operator to check if `target` exists in `obj`.
|
||||
If found, return the value of `obj[target]`, otherwise use `Object.values(obj)` and `Array.prototype.reduce()` to recursively call `dig` on each nested object until the first matching key/value pair is found.
|
||||
- Use the `in` operator to check if `target` exists in `obj`.
|
||||
- If found, return the value of `obj[target]`, otherwise use `Object.values(obj)` and `Array.prototype.reduce()` to recursively call `dig` on each nested object until the first matching key/value pair is found.
|
||||
|
||||
```js
|
||||
const dig = (obj, target) =>
|
||||
|
||||
@ -5,8 +5,8 @@ tags: math,array,beginner
|
||||
|
||||
Converts a number to an array of digits.
|
||||
|
||||
Convert the number to a string, using the spread operator (`...`) to build an array.
|
||||
Use `Array.prototype.map()` and `parseInt()` to transform each value to an integer.
|
||||
- Convert the number to a string, using the spread operator (`...`) to build an array.
|
||||
- Use `Array.prototype.map()` and `parseInt()` to transform each value to an integer.
|
||||
|
||||
```js
|
||||
const digitize = n => [...`${n}`].map(i => parseInt(i));
|
||||
|
||||
@ -5,7 +5,7 @@ tags: math,beginner
|
||||
|
||||
Returns the distance between two points.
|
||||
|
||||
Use `Math.hypot()` to calculate the Euclidean distance between two points.
|
||||
- Use `Math.hypot()` to calculate the Euclidean distance between two points.
|
||||
|
||||
```js
|
||||
const distance = (x0, y0, x1, y1) => Math.hypot(x1 - x0, y1 - y0);
|
||||
|
||||
@ -5,7 +5,7 @@ tags: array,beginner
|
||||
|
||||
Returns a new array with `n` elements removed from the left.
|
||||
|
||||
Use `Array.prototype.slice()` to remove the specified number of elements from the left.
|
||||
- Use `Array.prototype.slice()` to remove the specified number of elements from the left.
|
||||
|
||||
```js
|
||||
const drop = (arr, n = 1) => arr.slice(n);
|
||||
|
||||
@ -5,7 +5,7 @@ tags: array,beginner
|
||||
|
||||
Returns a new array with `n` elements removed from the right.
|
||||
|
||||
Use `Array.prototype.slice()` to remove the specified number of elements from the right.
|
||||
- Use `Array.prototype.slice()` to remove the specified number of elements from the right.
|
||||
|
||||
```js
|
||||
const dropRight = (arr, n = 1) => arr.slice(0, -n);
|
||||
|
||||
@ -5,8 +5,8 @@ tags: array,function,intermediate
|
||||
|
||||
Removes elements from the end of an array until the passed function returns `true`. Returns the remaining elements in the array.
|
||||
|
||||
Loop through the array, using `Array.prototype.slice()` to drop the last element of the array until the returned value from the function is `true`.
|
||||
Returns the remaining elements.
|
||||
- Loop through the array, using `Array.prototype.slice()` to drop the last element of the array until the returned value from the function is `true`.
|
||||
- Returns the remaining elements.
|
||||
|
||||
```js
|
||||
const dropRightWhile = (arr, func) => {
|
||||
|
||||
@ -5,8 +5,8 @@ tags: array,function,intermediate
|
||||
|
||||
Removes elements in an array until the passed function returns `true`. Returns the remaining elements in the array.
|
||||
|
||||
Loop through the array, using `Array.prototype.slice()` to drop the first element of the array until the returned value from the function is `true`.
|
||||
Returns the remaining elements.
|
||||
- Loop through the array, using `Array.prototype.slice()` to drop the first element of the array until the returned value from the function is `true`.
|
||||
- Returns the remaining elements.
|
||||
|
||||
```js
|
||||
const dropWhile = (arr, func) => {
|
||||
|
||||
@ -5,7 +5,7 @@ tags: function,logic,beginner
|
||||
|
||||
Returns `true` if at least one function returns `true` for a given set of arguments, `false` otherwise.
|
||||
|
||||
Use the logical or (`||`) operator on the result of calling the two functions with the supplied `args`.
|
||||
- Use the logical or (`||`) operator on the result of calling the two functions with the supplied `args`.
|
||||
|
||||
```js
|
||||
const either = (f, g) => (...args) => f(...args) || g(...args);
|
||||
|
||||
@ -5,7 +5,7 @@ tags: browser,intermediate
|
||||
|
||||
Returns `true` if the `parent` element contains the `child` element, `false` otherwise.
|
||||
|
||||
Check that `parent` is not the same element as `child`, use `parent.contains(child)` to check if the `parent` element contains the `child` element.
|
||||
- Check that `parent` is not the same element as `child`, use `parent.contains(child)` to check if the `parent` element contains the `child` element.
|
||||
|
||||
```js
|
||||
const elementContains = (parent, child) => parent !== child && parent.contains(child);
|
||||
|
||||
@ -5,7 +5,7 @@ tags: browser,intermediate
|
||||
|
||||
Returns `true` if the given element is focused, `false` otherwise.
|
||||
|
||||
Use `document.activeElement` to determine if the given element is focused.
|
||||
- Use `document.activeElement` to determine if the given element is focused.
|
||||
|
||||
```js
|
||||
const elementIsFocused = el => (el === document.activeElement);
|
||||
|
||||
@ -5,10 +5,9 @@ tags: browser,advanced
|
||||
|
||||
Returns `true` if the element specified is visible in the viewport, `false` otherwise.
|
||||
|
||||
Use `Element.getBoundingClientRect()` and the `window.inner(Width|Height)` values
|
||||
to determine if a given element is visible in the viewport.
|
||||
Omit the second argument to determine if the element is entirely visible, or specify `true` to determine if
|
||||
it is partially visible.
|
||||
- Use `Element.getBoundingClientRect()` and the `window.inner(Width|Height)` values
|
||||
- to determine if a given element is visible in the viewport.
|
||||
- Omit the second argument to determine if the element is entirely visible, or specify `true` to determine if it is partially visible.
|
||||
|
||||
```js
|
||||
const elementIsVisibleInViewport = (el, partiallyVisible = false) => {
|
||||
|
||||
@ -7,10 +7,9 @@ Computes the new ratings between two or more opponents using the [Elo rating sys
|
||||
of pre-ratings and returns an array containing post-ratings.
|
||||
The array should be ordered from best performer to worst performer (winner -> loser).
|
||||
|
||||
Use the exponent `**` operator and math operators to compute the expected score (chance of winning).
|
||||
of each opponent and compute the new rating for each.
|
||||
Loop through the ratings, using each permutation to compute the post-Elo rating for each player in a pairwise fashion.
|
||||
Omit the second argument to use the default `kFactor` of 32.
|
||||
- Use the exponent `**` operator and math operators to compute the expected score (chance of winning) of each opponent and compute the new rating for each.
|
||||
- Loop through the ratings, using each permutation to compute the post-Elo rating for each player in a pairwise fashion.
|
||||
- Omit the second argument to use the default `kFactor` of 32.
|
||||
|
||||
```js
|
||||
const elo = ([...ratings], kFactor = 32, selfRating) => {
|
||||
|
||||
@ -5,9 +5,9 @@ tags: object,array,type,advanced
|
||||
|
||||
Performs a deep comparison between two values to determine if they are equivalent.
|
||||
|
||||
Check if the two values are identical, if they are both `Date` objects with the same time, using `Date.getTime()` or if they are both non-object values with an equivalent value (strict comparison).
|
||||
Check if only one value is `null` or `undefined` or if their prototypes differ.
|
||||
If none of the above conditions are met, use `Object.keys()` to check if both values have the same number of keys, then use `Array.prototype.every()` to check if every key in the first value exists in the second one and if they are equivalent by calling this method recursively.
|
||||
- Check if the two values are identical, if they are both `Date` objects with the same time, using `Date.getTime()` or if they are both non-object values with an equivalent value (strict comparison).
|
||||
- Check if only one value is `null` or `undefined` or if their prototypes differ.
|
||||
- If none of the above conditions are met, use `Object.keys()` to check if both values have the same number of keys, then use `Array.prototype.every()` to check if every key in the first value exists in the second one and if they are equivalent by calling this method recursively.
|
||||
|
||||
```js
|
||||
const equals = (a, b) => {
|
||||
|
||||
@ -5,7 +5,7 @@ tags: string,browser,regexp,intermediate
|
||||
|
||||
Escapes a string for use in HTML.
|
||||
|
||||
Use `String.prototype.replace()` with a regexp that matches the characters that need to be escaped, using a callback function to replace each character instance with its associated escaped character using a dictionary (object).
|
||||
- Use `String.prototype.replace()` with a regexp that matches the characters that need to be escaped, using a callback function to replace each character instance with its associated escaped character using a dictionary (object).
|
||||
|
||||
```js
|
||||
const escapeHTML = str =>
|
||||
|
||||
@ -5,7 +5,7 @@ tags: string,regexp,intermediate
|
||||
|
||||
Escapes a string to use in a regular expression.
|
||||
|
||||
Use `String.prototype.replace()` to escape special characters.
|
||||
- Use `String.prototype.replace()` to escape special characters.
|
||||
|
||||
```js
|
||||
const escapeRegExp = str => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||
|
||||
@ -5,7 +5,7 @@ tags: array,beginner
|
||||
|
||||
Returns every nth element in an array.
|
||||
|
||||
Use `Array.prototype.filter()` to create a new array that contains every nth element of a given array.
|
||||
- Use `Array.prototype.filter()` to create a new array that contains every nth element of a given array.
|
||||
|
||||
```js
|
||||
const everyNth = (arr, nth) => arr.filter((e, i) => i % nth === nth - 1);
|
||||
|
||||
@ -5,7 +5,7 @@ tags: string,regexp,beginner
|
||||
|
||||
Convert tabs to spaces, where each tab corresponds to `count` spaces.
|
||||
|
||||
Use `String.prototype.replace()` with a regular expression and `String.prototype.repeat()` to replace each tab character with `count` spaces.
|
||||
- Use `String.prototype.replace()` with a regular expression and `String.prototype.repeat()` to replace each tab character with `count` spaces.
|
||||
|
||||
```js
|
||||
const expandTabs = (str, count) => str.replace(/\t/g, ' '.repeat(count));
|
||||
|
||||
@ -5,8 +5,8 @@ tags: string,intermediate
|
||||
|
||||
Extends a 3-digit color code to a 6-digit color code.
|
||||
|
||||
Use `Array.prototype.map()`, `String.prototype.split()` and `Array.prototype.join()` to join the mapped array for converting a 3-digit RGB notated hexadecimal color-code to the 6-digit form.
|
||||
`Array.prototype.slice()` is used to remove `#` from string start since it's added once.
|
||||
- Use `Array.prototype.map()`, `String.prototype.split()` and `Array.prototype.join()` to join the mapped array for converting a 3-digit RGB notated hexadecimal color-code to the 6-digit form.
|
||||
- `Array.prototype.slice()` is used to remove `#` from string start since it's added once.
|
||||
|
||||
```js
|
||||
const extendHex = shortHex =>
|
||||
|
||||
@ -5,10 +5,10 @@ tags: math,recursion,beginner
|
||||
|
||||
Calculates the factorial of a number.
|
||||
|
||||
Use recursion.
|
||||
If `n` is less than or equal to `1`, return `1`.
|
||||
Otherwise, return the product of `n` and the factorial of `n - 1`.
|
||||
Throws an exception if `n` is a negative number.
|
||||
- Use recursion.
|
||||
- If `n` is less than or equal to `1`, return `1`.
|
||||
- Otherwise, return the product of `n` and the factorial of `n - 1`.
|
||||
- Throws an exception if `n` is a negative number.
|
||||
|
||||
```js
|
||||
const factorial = n =>
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user