Update snippet descriptions
This commit is contained in:
@ -3,7 +3,7 @@ title: objectToQueryString
|
||||
tags: object,advanced
|
||||
---
|
||||
|
||||
Returns a query string generated from the key-value pairs of the given object.
|
||||
Generates a query string from the key-value pairs of the given object.
|
||||
|
||||
- Use `Array.prototype.reduce()` on `Object.entries(queryParameters)` to create the query string.
|
||||
- Determine the `symbol` to be either `?` or `&` based on the length of `queryString`.
|
||||
|
||||
@ -3,7 +3,7 @@ title: observeMutations
|
||||
tags: browser,event,advanced
|
||||
---
|
||||
|
||||
Returns a new `MutationObserver` and runs the provided callback for each mutation on the specified element.
|
||||
Creates a new `MutationObserver` and runs the provided callback for each mutation on the specified element.
|
||||
|
||||
- Use a [`MutationObserver`](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver) to observe mutations on the given element.
|
||||
- Use `Array.prototype.forEach()` to run the callback for each mutation that is observed.
|
||||
|
||||
@ -3,7 +3,7 @@ title: pad
|
||||
tags: string,beginner
|
||||
---
|
||||
|
||||
Pads a string on both sides with the specified character, if it's shorter than the specified length.
|
||||
Pads a string on both sides with the specified character, if it's shorter than the specified `length`.
|
||||
|
||||
- Use `String.prototype.padStart()` and `String.prototype.padEnd()` to pad both sides of the given string.
|
||||
- Omit the third argument, `char`, to use the whitespace character as the default padding character.
|
||||
|
||||
@ -3,10 +3,11 @@ title: palindrome
|
||||
tags: string,intermediate
|
||||
---
|
||||
|
||||
Returns `true` if the given string is a palindrome, `false` otherwise.
|
||||
Checks if the given string is a palindrome.
|
||||
|
||||
- Convert the string to `String.prototype.toLowerCase()` and use `String.prototype.replace()` to remove non-alphanumeric characters from it.
|
||||
- Then, use the spread operator (`...`) to split the string into individual characters, `Array.prototype.reverse()`, `String.prototype.join('')` and compare it to the original, unreversed string, after converting it to `String.prototype.toLowerCase()`.
|
||||
- Normalize the string to `String.prototype.toLowerCase()` and use `String.prototype.replace()` to remove non-alphanumeric characters from it.
|
||||
- Use the spread operator (`...`) to split the normalized string into individual characters.
|
||||
- Use `Array.prototype.reverse()`, `String.prototype.join('')` and compare the result to the normalized string.
|
||||
|
||||
```js
|
||||
const palindrome = str => {
|
||||
|
||||
@ -3,7 +3,7 @@ title: parseCookie
|
||||
tags: browser,string,intermediate
|
||||
---
|
||||
|
||||
Parse an HTTP Cookie header string and return an object of all cookie name-value pairs.
|
||||
Parses an HTTP Cookie header string, returning an object of all cookie name-value pairs.
|
||||
|
||||
- Use `String.prototype.split(';')` to separate key-value pairs from each other.
|
||||
- Use `Array.prototype.map()` and `String.prototype.split('=')` to separate keys from values in each pair.
|
||||
@ -21,5 +21,6 @@ const parseCookie = str =>
|
||||
```
|
||||
|
||||
```js
|
||||
parseCookie('foo=bar; equation=E%3Dmc%5E2'); // { foo: 'bar', equation: 'E=mc^2' }
|
||||
parseCookie('foo=bar; equation=E%3Dmc%5E2');
|
||||
// { foo: 'bar', equation: 'E=mc^2' }
|
||||
```
|
||||
|
||||
@ -20,6 +20,10 @@ const partition = (arr, fn) =>
|
||||
```
|
||||
|
||||
```js
|
||||
const users = [{ user: 'barney', age: 36, active: false }, { user: 'fred', age: 40, active: true }];
|
||||
partition(users, o => o.active); // [[{ 'user': 'fred', 'age': 40, 'active': true }],[{ 'user': 'barney', 'age': 36, 'active': false }]]
|
||||
const users = [
|
||||
{ user: 'barney', age: 36, active: false },
|
||||
{ user: 'fred', age: 40, active: true },
|
||||
];
|
||||
partition(users, o => o.active);
|
||||
// [[{ 'user': 'fred', 'age': 40, 'active': true }],[{ 'user': 'barney', 'age': 36, 'active': false }]]
|
||||
```
|
||||
|
||||
@ -3,7 +3,7 @@ title: partitionBy
|
||||
tags: array,object,advanced
|
||||
---
|
||||
|
||||
Applies `fn` to each value in `arr`, splitting it each time `fn` returns a new value.
|
||||
Applies `fn` to each value in `arr`, splitting it each time the provided function returns a new value.
|
||||
|
||||
- Use `Array.prototype.reduce()` with an accumulator object that will hold the resulting array and the last value returned from `fn`.
|
||||
- Use `Array.prototype.push()` to add each value in `arr` to the appropriate partition in the accumulator array.
|
||||
|
||||
@ -3,13 +3,18 @@ title: percentile
|
||||
tags: math,intermediate
|
||||
---
|
||||
|
||||
Uses the percentile formula to calculate how many numbers in the given array are less or equal to the given value.
|
||||
Calculates the percentage of numbers in the given array that are less or equal to the given value.
|
||||
|
||||
- Use `Array.prototype.reduce()` to calculate how many numbers are below the value and how many are the same value and apply the percentile formula.
|
||||
|
||||
```js
|
||||
const percentile = (arr, val) =>
|
||||
(100 * arr.reduce((acc, v) => acc + (v < val ? 1 : 0) + (v === val ? 0.5 : 0), 0)) / arr.length;
|
||||
(100 *
|
||||
arr.reduce(
|
||||
(acc, v) => acc + (v < val ? 1 : 0) + (v === val ? 0.5 : 0),
|
||||
0
|
||||
)) /
|
||||
arr.length;
|
||||
```
|
||||
|
||||
```js
|
||||
|
||||
@ -9,7 +9,7 @@ Generates all permutations of an array's elements (contains duplicates).
|
||||
- For each element in the given array, create all the partial permutations for the rest of its elements.
|
||||
- Use `Array.prototype.map()` to combine the element with each partial permutation, then `Array.prototype.reduce()` to combine all permutations in one array.
|
||||
- Base cases are for `Array.prototype.length` equal to `2` or `1`.
|
||||
- ⚠️ **WARNING**: This function's execution time increases exponentially with each array element. Anything more than 8 to 10 entries will cause your browser to hang as it tries to solve all the different combinations.
|
||||
- ⚠️ **WARNING**: This function's execution time increases exponentially with each array element. Anything more than 8 to 10 entries may cause your browser to hang as it tries to solve all the different combinations.
|
||||
|
||||
```js
|
||||
const permutations = arr => {
|
||||
@ -17,7 +17,10 @@ const permutations = arr => {
|
||||
return arr.reduce(
|
||||
(acc, item, i) =>
|
||||
acc.concat(
|
||||
permutations([...arr.slice(0, i), ...arr.slice(i + 1)]).map(val => [item, ...val])
|
||||
permutations([...arr.slice(0, i), ...arr.slice(i + 1)]).map(val => [
|
||||
item,
|
||||
...val,
|
||||
])
|
||||
),
|
||||
[]
|
||||
);
|
||||
@ -25,5 +28,6 @@ const permutations = arr => {
|
||||
```
|
||||
|
||||
```js
|
||||
permutations([1, 33, 5]); // [ [ 1, 33, 5 ], [ 1, 5, 33 ], [ 33, 1, 5 ], [ 33, 5, 1 ], [ 5, 1, 33 ], [ 5, 33, 1 ] ]
|
||||
permutations([1, 33, 5]);
|
||||
// [ [1, 33, 5], [1, 5, 33], [33, 1, 5], [33, 5, 1], [5, 1, 33], [5, 33, 1] ]
|
||||
```
|
||||
|
||||
@ -3,10 +3,11 @@ title: pickBy
|
||||
tags: object,intermediate
|
||||
---
|
||||
|
||||
Creates an object composed of the properties the given function returns truthy for. The function is invoked with two arguments: (value, key).
|
||||
Creates an object composed of the properties the given function returns truthy for.
|
||||
|
||||
- Use `Object.keys(obj)` and `Array.prototype.filter()`to remove the keys for which `fn` returns a falsy value.
|
||||
- Use `Array.prototype.reduce()` to convert the filtered keys back to an object with the corresponding key-value pairs.
|
||||
- The callback function is invoked with two arguments: (value, key).
|
||||
|
||||
```js
|
||||
const pickBy = (obj, fn) =>
|
||||
@ -16,5 +17,6 @@ const pickBy = (obj, fn) =>
|
||||
```
|
||||
|
||||
```js
|
||||
pickBy({ a: 1, b: '2', c: 3 }, x => typeof x === 'number'); // { 'a': 1, 'c': 3 }
|
||||
pickBy({ a: 1, b: '2', c: 3 }, x => typeof x === 'number');
|
||||
// { 'a': 1, 'c': 3 }
|
||||
```
|
||||
|
||||
@ -5,16 +5,16 @@ tags: function,promise,intermediate
|
||||
|
||||
Performs left-to-right function composition for asynchronous functions.
|
||||
|
||||
- Use `Array.prototype.reduce()` and the spread operator (`...`) to perform function composition using `Promise.then()`.
|
||||
- Use `Array.prototype.reduce()` and the spread operator (`...`) to perform function composition using `Promise.prototype.then()`.
|
||||
- The functions can return a combination of normal values, `Promise`s or be `async`, returning through `await`.
|
||||
- All functions must accept a single argument.
|
||||
|
||||
```js
|
||||
const pipeAsyncFunctions = (...fns) => arg => fns.reduce((p, f) => p.then(f), Promise.resolve(arg));
|
||||
const pipeAsyncFunctions = (...fns) =>
|
||||
arg => fns.reduce((p, f) => p.then(f), Promise.resolve(arg));
|
||||
```
|
||||
|
||||
```js
|
||||
|
||||
const sum = pipeAsyncFunctions(
|
||||
x => x + 1,
|
||||
x => new Promise(resolve => setTimeout(() => resolve(x + 2), 1000)),
|
||||
|
||||
@ -9,7 +9,8 @@ Performs left-to-right function composition.
|
||||
- The first (leftmost) function can accept one or more arguments; the remaining functions must be unary.
|
||||
|
||||
```js
|
||||
const pipeFunctions = (...fns) => fns.reduce((f, g) => (...args) => g(f(...args)));
|
||||
const pipeFunctions = (...fns) =>
|
||||
fns.reduce((f, g) => (...args) => g(f(...args)));
|
||||
```
|
||||
|
||||
```js
|
||||
|
||||
@ -16,7 +16,7 @@ const simpsons = [
|
||||
{ name: 'lisa', age: 8 },
|
||||
{ name: 'homer', age: 36 },
|
||||
{ name: 'marge', age: 34 },
|
||||
{ name: 'bart', age: 10 },
|
||||
{ name: 'bart', age: 10 }
|
||||
];
|
||||
pluck(simpsons, 'age'); // [8, 36, 34, 10]
|
||||
```
|
||||
|
||||
@ -1,20 +1,22 @@
|
||||
---
|
||||
title: pluralize
|
||||
tags: string,intermediate
|
||||
tags: string,advanced
|
||||
---
|
||||
|
||||
Returns the singular or plural form of the word based on the input number. If the first argument is an `object`, it will use a closure by returning a function that can auto-pluralize words that don't simply end in `s` if the supplied dictionary contains the word.
|
||||
Returns the singular or plural form of the word based on the input number, using an optional dictionary if supplied.
|
||||
|
||||
- Use a closure to define a function that pluralizes the given `word` based on the value of `num`.
|
||||
- If `num` is either `-1` or `1`, return the singular form of the word.
|
||||
- If `num` is any other number, return the plural form.
|
||||
- Omit the third argument to use the default of the singular word + `s`, or supply a custom pluralized word when necessary.
|
||||
- If the first argument is an `object`, utilize a closure by returning a function which can use the supplied dictionary to resolve the correct plural form of the word.
|
||||
- If `num` is any other number, return the `plural` form.
|
||||
- Omit the third argument, `plural`, to use the default of the singular word + `s`, or supply a custom pluralized `word` when necessary.
|
||||
- If the first argument is an `object`, return a function which can use the supplied dictionary to resolve the correct plural form of the word.
|
||||
|
||||
```js
|
||||
const pluralize = (val, word, plural = word + 's') => {
|
||||
const _pluralize = (num, word, plural = word + 's') =>
|
||||
[1, -1].includes(Number(num)) ? word : plural;
|
||||
if (typeof val === 'object') return (num, word) => _pluralize(num, word, val[word]);
|
||||
if (typeof val === 'object')
|
||||
return (num, word) => _pluralize(num, word, val[word]);
|
||||
return _pluralize(val, word, plural);
|
||||
};
|
||||
```
|
||||
|
||||
@ -8,7 +8,8 @@ Returns the powerset of a given array of numbers.
|
||||
- Use `Array.prototype.reduce()` combined with `Array.prototype.map()` to iterate over elements and combine into an array containing all combinations.
|
||||
|
||||
```js
|
||||
const powerset = arr => arr.reduce((a, v) => a.concat(a.map(r => [v].concat(r))), [[]]);
|
||||
const powerset = arr =>
|
||||
arr.reduce((a, v) => a.concat(a.map(r => [v].concat(r))), [[]]);
|
||||
```
|
||||
|
||||
```js
|
||||
|
||||
@ -3,13 +3,15 @@ title: prefersDarkColorScheme
|
||||
tags: browser,intermediate
|
||||
---
|
||||
|
||||
Returns `true` if the user color scheme preference is `dark`, `false` otherwise.
|
||||
Checks if the user color scheme preference is `dark`.
|
||||
|
||||
- Use `Window.matchMedia()` with the appropriate media query to check the user color scheme preference.
|
||||
|
||||
```js
|
||||
const prefersDarkColorScheme = () =>
|
||||
window && window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
|
||||
window &&
|
||||
window.matchMedia &&
|
||||
window.matchMedia('(prefers-color-scheme: dark)').matches;
|
||||
```
|
||||
|
||||
```js
|
||||
|
||||
@ -3,13 +3,15 @@ title: prefersLightColorScheme
|
||||
tags: browser,intermediate
|
||||
---
|
||||
|
||||
Returns `true` if the user color scheme preference is `light`, `false` otherwise.
|
||||
Checks if the user color scheme preference is `light`.
|
||||
|
||||
- Use `Window.matchMedia()` with the appropriate media query to check the user color scheme preference.
|
||||
|
||||
```js
|
||||
const prefersLightColorScheme = () =>
|
||||
window && window.matchMedia && window.matchMedia('(prefers-color-scheme: light)').matches;
|
||||
window &&
|
||||
window.matchMedia &&
|
||||
window.matchMedia('(prefers-color-scheme: light)').matches;
|
||||
```
|
||||
|
||||
```js
|
||||
|
||||
@ -3,7 +3,7 @@ title: prefix
|
||||
tags: browser,intermediate
|
||||
---
|
||||
|
||||
Returns the prefixed version (if necessary) of a CSS property that the browser supports.
|
||||
Prefixes a CSS property based on the current browser.
|
||||
|
||||
- Use `Array.prototype.findIndex()` on an array of vendor prefix strings to test if `Document.body` has one of them defined in its `CSSStyleDeclaration` object, otherwise return `null`.
|
||||
- Use `String.prototype.charAt()` and `String.prototype.toUpperCase()` to capitalize the property, which will be appended to the vendor prefix string.
|
||||
@ -13,12 +13,15 @@ const prefix = prop => {
|
||||
const capitalizedProp = prop.charAt(0).toUpperCase() + prop.slice(1);
|
||||
const prefixes = ['', 'webkit', 'moz', 'ms', 'o'];
|
||||
const i = prefixes.findIndex(
|
||||
prefix => typeof document.body.style[prefix ? prefix + capitalizedProp : prop] !== 'undefined'
|
||||
prefix =>
|
||||
typeof document.body.style[prefix ? prefix + capitalizedProp : prop] !==
|
||||
'undefined'
|
||||
);
|
||||
return i !== -1 ? (i === 0 ? prop : prefixes[i] + capitalizedProp) : null;
|
||||
};
|
||||
```
|
||||
|
||||
```js
|
||||
prefix('appearance'); // 'appearance' on a supported browser, otherwise 'webkitAppearance', 'mozAppearance', 'msAppearance' or 'oAppearance'
|
||||
prefix('appearance');
|
||||
// 'appearance' on a supported browser, otherwise 'webkitAppearance', 'mozAppearance', 'msAppearance' or 'oAppearance'
|
||||
```
|
||||
|
||||
@ -15,8 +15,13 @@ Converts a number in bytes to a human-readable string.
|
||||
const prettyBytes = (num, precision = 3, addSpace = true) => {
|
||||
const UNITS = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
|
||||
if (Math.abs(num) < 1) return num + (addSpace ? ' ' : '') + UNITS[0];
|
||||
const exponent = Math.min(Math.floor(Math.log10(num < 0 ? -num : num) / 3), UNITS.length - 1);
|
||||
const n = Number(((num < 0 ? -num : num) / 1000 ** exponent).toPrecision(precision));
|
||||
const exponent = Math.min(
|
||||
Math.floor(Math.log10(num < 0 ? -num : num) / 3),
|
||||
UNITS.length - 1
|
||||
);
|
||||
const n = Number(
|
||||
((num < 0 ? -num : num) / 1000 ** exponent).toPrecision(precision)
|
||||
);
|
||||
return (num < 0 ? '-' : '') + n + (addSpace ? ' ' : '') + UNITS[exponent];
|
||||
};
|
||||
```
|
||||
|
||||
@ -19,5 +19,5 @@ const primes = num => {
|
||||
```
|
||||
|
||||
```js
|
||||
primes(10); // [2,3,5,7]
|
||||
primes(10); // [2, 3, 5, 7]
|
||||
```
|
||||
|
||||
@ -3,7 +3,7 @@ title: prod
|
||||
tags: math,array,intermediate
|
||||
---
|
||||
|
||||
Returns the product of two or more numbers/arrays.
|
||||
Calculates the product of two or more numbers/arrays.
|
||||
|
||||
- Use `Array.prototype.reduce()` to multiply each value with an accumulator, initialized with a value of `1`.
|
||||
|
||||
|
||||
@ -6,8 +6,8 @@ tags: function,promise,intermediate
|
||||
Converts an asynchronous function to return a promise.
|
||||
|
||||
- Use currying to return a function returning a `Promise` that calls the original function.
|
||||
- Use the `...rest` operator to pass in all the parameters.
|
||||
- *In Node 8+, you can use [`util.promisify`](https://nodejs.org/api/util.html#util_util_promisify_original)*
|
||||
- Use the rest operator (`...`) to pass in all the parameters.
|
||||
- **Note:** In Node 8+, you can use [`util.promisify`](https://nodejs.org/api/util.html#util_util_promisify_original).
|
||||
|
||||
```js
|
||||
const promisify = func => (...args) =>
|
||||
@ -18,5 +18,5 @@ const promisify = func => (...args) =>
|
||||
|
||||
```js
|
||||
const delay = promisify((d, cb) => setTimeout(cb, d));
|
||||
delay(2000).then(() => console.log('Hi!')); // // Promise resolves after 2s
|
||||
delay(2000).then(() => console.log('Hi!')); // Promise resolves after 2s
|
||||
```
|
||||
|
||||
@ -6,7 +6,8 @@ tags: array,intermediate
|
||||
Mutates the original array to filter out the values specified.
|
||||
|
||||
- Use `Array.prototype.filter()` and `Array.prototype.includes()` to pull out the values that are not needed.
|
||||
- Use `Array.prototype.length = 0` to mutate the passed in an array by resetting it's length to zero and `Array.prototype.push()` to re-populate it with only the pulled values.
|
||||
- Set `Array.prototype.length` to mutate the passed in an array by resetting its length to `0`.
|
||||
- Use `Array.prototype.push()` to re-populate it with only the pulled values.
|
||||
|
||||
```js
|
||||
const pull = (arr, ...args) => {
|
||||
|
||||
@ -4,10 +4,12 @@ tags: array,advanced
|
||||
---
|
||||
|
||||
Mutates the original array to filter out the values at the specified indexes.
|
||||
Returns the removed elements.
|
||||
|
||||
- Use `Array.prototype.filter()` and `Array.prototype.includes()` to pull out the values that are not needed.
|
||||
- Use `Array.prototype.length = 0` to mutate the passed in an array by resetting it's length to zero and `Array.prototype.push()` to re-populate it with only the pulled values.
|
||||
- Use `Array.prototype.push()` to keep track of pulled values
|
||||
- Set `Array.prototype.length` to mutate the passed in an array by resetting its length to `0`.
|
||||
- Use `Array.prototype.push()` to re-populate it with only the pulled values.
|
||||
- Use `Array.prototype.push()` to keep track of pulled values.
|
||||
|
||||
```js
|
||||
const pullAtIndex = (arr, pullArr) => {
|
||||
@ -23,5 +25,6 @@ const pullAtIndex = (arr, pullArr) => {
|
||||
|
||||
```js
|
||||
let myArray = ['a', 'b', 'c', 'd'];
|
||||
let pulled = pullAtIndex(myArray, [1, 3]); // myArray = [ 'a', 'c' ] , pulled = [ 'b', 'd' ]
|
||||
let pulled = pullAtIndex(myArray, [1, 3]);
|
||||
// myArray = [ 'a', 'c' ] , pulled = [ 'b', 'd' ]
|
||||
```
|
||||
|
||||
@ -3,16 +3,20 @@ title: pullAtValue
|
||||
tags: array,advanced
|
||||
---
|
||||
|
||||
Mutates the original array to filter out the values specified. Returns the removed elements.
|
||||
Mutates the original array to filter out the values specified.
|
||||
Returns the removed elements.
|
||||
|
||||
- Use `Array.prototype.filter()` and `Array.prototype.includes()` to pull out the values that are not needed.
|
||||
- Use `Array.prototype.length = 0` to mutate the passed in an array by resetting it's length to zero and `Array.prototype.push()` to re-populate it with only the pulled values.
|
||||
- Use `Array.prototype.push()` to keep track of pulled values
|
||||
- Set `Array.prototype.length` to mutate the passed in an array by resetting its length to `0`.
|
||||
- Use `Array.prototype.push()` to re-populate it with only the pulled values.
|
||||
- Use `Array.prototype.push()` to keep track of pulled values.
|
||||
|
||||
```js
|
||||
const pullAtValue = (arr, pullArr) => {
|
||||
let removed = [],
|
||||
pushToRemove = arr.forEach((v, i) => (pullArr.includes(v) ? removed.push(v) : v)),
|
||||
pushToRemove = arr.forEach((v, i) =>
|
||||
pullArr.includes(v) ? removed.push(v) : v
|
||||
),
|
||||
mutateTo = arr.filter((v, i) => !pullArr.includes(v));
|
||||
arr.length = 0;
|
||||
mutateTo.forEach(v => arr.push(v));
|
||||
@ -22,5 +26,6 @@ const pullAtValue = (arr, pullArr) => {
|
||||
|
||||
```js
|
||||
let myArray = ['a', 'b', 'c', 'd'];
|
||||
let pulled = pullAtValue(myArray, ['b', 'd']); // myArray = [ 'a', 'c' ] , pulled = [ 'b', 'd' ]
|
||||
let pulled = pullAtValue(myArray, ['b', 'd']);
|
||||
// myArray = [ 'a', 'c' ] , pulled = [ 'b', 'd' ]
|
||||
```
|
||||
|
||||
@ -5,10 +5,11 @@ tags: array,advanced
|
||||
|
||||
Mutates the original array to filter out the values specified, based on a given iterator function.
|
||||
|
||||
- Check if the last argument provided in a function.
|
||||
- Check if the last argument provided is a function.
|
||||
- Use `Array.prototype.map()` to apply the iterator function `fn` to all array elements.
|
||||
- Use `Array.prototype.filter()` and `Array.prototype.includes()` to pull out the values that are not needed.
|
||||
- Use `Array.prototype.length = 0` to mutate the passed in an array by resetting it's length to zero and `Array.prototype.push()` to re-populate it with only the pulled values.
|
||||
- Set `Array.prototype.length` to mutate the passed in an array by resetting its length to `0`.
|
||||
- Use `Array.prototype.push()` to re-populate it with only the pulled values.
|
||||
|
||||
```js
|
||||
const pullBy = (arr, ...args) => {
|
||||
|
||||
@ -7,13 +7,13 @@ Returns the quarter and year to which the supplied date belongs to.
|
||||
|
||||
- Use `Date.prototype.getMonth()` to get the current month in the range (0, 11), add `1` to map it to the range (1, 12).
|
||||
- Use `Math.ceil()` and divide the month by `3` to get the current quarter.
|
||||
- Use `Date.prototype.getFullYear()` to get the year from the given date.
|
||||
- Use `Date.prototype.getFullYear()` to get the year from the given `date`.
|
||||
- Omit the argument, `date`, to use the current date by default.
|
||||
|
||||
```js
|
||||
const quarterOfYear = (date = new Date()) => [
|
||||
Math.ceil((date.getMonth() + 1) / 3),
|
||||
date.getFullYear(),
|
||||
date.getFullYear()
|
||||
];
|
||||
```
|
||||
|
||||
|
||||
@ -3,7 +3,7 @@ title: randomAlphaNumeric
|
||||
tags: string,random,advanced
|
||||
---
|
||||
|
||||
Returns a random string with the specified length.
|
||||
Generates a random string with the specified length.
|
||||
|
||||
- Use `Array.from()` to create a new array with the specified `length`.
|
||||
- Use `Math.random()` generate a random floating-point number, `Number.prototype.toString(36)` to convert it to an alphanumeric string.
|
||||
|
||||
@ -5,8 +5,8 @@ tags: math,random,beginner
|
||||
|
||||
Generates a random hexadecimal color code.
|
||||
|
||||
- Use `Math.random` to generate a random 24-bit(6x4bits) hexadecimal number.
|
||||
- Use bit shifting and then convert it to an hexadecimal String using `toString(16)`.
|
||||
- Use `Math.rando()m` to generate a random 24-bit (6 * 4bits) hexadecimal number.
|
||||
- Use bit shifting and then convert it to an hexadecimal string using `Number.prototype.toString(16)`.
|
||||
|
||||
```js
|
||||
const randomHexColorCode = () => {
|
||||
|
||||
@ -3,13 +3,17 @@ title: randomIntArrayInRange
|
||||
tags: math,random,intermediate
|
||||
---
|
||||
|
||||
Returns an array of n random integers in the specified range.
|
||||
Generates an array of `n` random integers in the specified range.
|
||||
|
||||
- Use `Array.from()` to create an empty array of the specific length, `Math.random()` to generate a random number and map it to the desired range, using `Math.floor()` to make it an integer.
|
||||
- Use `Array.from()` to create an empty array of the specific length.
|
||||
- Use `Math.random()` to generate random numbers and map them to the desired range, using `Math.floor()` to make them integers.
|
||||
|
||||
```js
|
||||
const randomIntArrayInRange = (min, max, n = 1) =>
|
||||
Array.from({ length: n }, () => Math.floor(Math.random() * (max - min + 1)) + min);
|
||||
Array.from(
|
||||
{ length: n },
|
||||
() => Math.floor(Math.random() * (max - min + 1)) + min
|
||||
);
|
||||
```
|
||||
|
||||
```js
|
||||
|
||||
@ -3,12 +3,14 @@ title: randomIntegerInRange
|
||||
tags: math,random,beginner
|
||||
---
|
||||
|
||||
Returns a random integer in the specified range.
|
||||
Generates a random integer in the specified range.
|
||||
|
||||
- Use `Math.random()` to generate a random number and map it to the desired range, using `Math.floor()` to make it an integer.
|
||||
- Use `Math.random()` to generate a random number and map it to the desired range.
|
||||
- Use `Math.floor()` to make it an integer.
|
||||
|
||||
```js
|
||||
const randomIntegerInRange = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
|
||||
const randomIntegerInRange = (min, max) =>
|
||||
Math.floor(Math.random() * (max - min + 1)) + min;
|
||||
```
|
||||
|
||||
```js
|
||||
|
||||
@ -3,7 +3,7 @@ title: randomNumberInRange
|
||||
tags: math,random,beginner
|
||||
---
|
||||
|
||||
Returns a random number in the specified range.
|
||||
Generates a random number in the specified range.
|
||||
|
||||
- Use `Math.random()` to generate a random value, map it to the desired range using multiplication.
|
||||
|
||||
|
||||
@ -1,13 +1,13 @@
|
||||
---
|
||||
title: readFileLines
|
||||
tags: node,beginner
|
||||
tags: node,array,beginner
|
||||
---
|
||||
|
||||
Returns an array of lines from the specified file.
|
||||
|
||||
- Use `readFileSync` function in `fs` node package to create a `Buffer` from a file.
|
||||
- Convert buffer to string using `toString(encoding)` function.
|
||||
- Use `split(\n)` to create an array of lines from the contents of the file.
|
||||
- Use `fs.readFileSync()` to create a `Buffer` from a file.
|
||||
- Convert buffer to string using `buf.toString(encoding)` function.
|
||||
- Use `String.prototype.split(\n)` to create an array of lines from the contents of the file.
|
||||
|
||||
```js
|
||||
const fs = require('fs');
|
||||
|
||||
@ -5,7 +5,8 @@ tags: function,intermediate
|
||||
|
||||
Creates a function that invokes the provided function with its arguments arranged according to the specified indexes.
|
||||
|
||||
- Use `Array.prototype.map()` to reorder arguments based on `indexes` in combination with the spread operator (`...`) to pass the transformed arguments to `fn`.
|
||||
- Use `Array.prototype.map()` to reorder arguments based on `indexes`.
|
||||
- Use the spread operator (`...`) to pass the transformed arguments to `fn`.
|
||||
|
||||
```js
|
||||
const rearg = (fn, indexes) => (...args) => fn(...indexes.map(i => args[i]));
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
---
|
||||
title: recordAnimationFrames
|
||||
tags: browser,intermediate
|
||||
tags: browser,recursion,intermediate
|
||||
---
|
||||
|
||||
Invokes the provided callback on each animation frame.
|
||||
@ -37,8 +37,10 @@ const recordAnimationFrames = (callback, autoStart = true) => {
|
||||
|
||||
```js
|
||||
const cb = () => console.log('Animation frame fired');
|
||||
const recorder = recordAnimationFrames(cb); // logs 'Animation frame fired' on each animation frame
|
||||
const recorder = recordAnimationFrames(cb);
|
||||
// logs 'Animation frame fired' on each animation frame
|
||||
recorder.stop(); // stops logging
|
||||
recorder.start(); // starts again
|
||||
const recorder2 = recordAnimationFrames(cb, false); // `start` needs to be explicitly called to begin recording frames
|
||||
const recorder2 = recordAnimationFrames(cb, false);
|
||||
// `start` needs to be explicitly called to begin recording frames
|
||||
```
|
||||
|
||||
@ -9,9 +9,13 @@ Applies a function against an accumulator and each element in the array (from le
|
||||
|
||||
```js
|
||||
const reduceSuccessive = (arr, fn, acc) =>
|
||||
arr.reduce((res, val, i, arr) => (res.push(fn(res.slice(-1)[0], val, i, arr)), res), [acc]);
|
||||
arr.reduce(
|
||||
(res, val, i, arr) => (res.push(fn(res.slice(-1)[0], val, i, arr)), res),
|
||||
[acc]
|
||||
);
|
||||
```
|
||||
|
||||
```js
|
||||
reduceSuccessive([1, 2, 3, 4, 5, 6], (acc, val) => acc + val, 0); // [0, 1, 3, 6, 10, 15, 21]
|
||||
reduceSuccessive([1, 2, 3, 4, 5, 6], (acc, val) => acc + val, 0);
|
||||
// [0, 1, 3, 6, 10, 15, 21]
|
||||
```
|
||||
|
||||
@ -3,7 +3,7 @@ title: reduceWhich
|
||||
tags: array,intermediate
|
||||
---
|
||||
|
||||
Returns the minimum/maximum value of an array, after applying the provided function to set comparing rule.
|
||||
Returns the minimum/maximum value of an array, after applying the provided function to set the comparing rule.
|
||||
|
||||
- Use `Array.prototype.reduce()` in combination with the `comparator` function to get the appropriate element in the array.
|
||||
- You can omit the second parameter, `comparator`, to use the default one that returns the minimum element in the array.
|
||||
|
||||
@ -3,10 +3,11 @@ title: reducedFilter
|
||||
tags: array,intermediate
|
||||
---
|
||||
|
||||
Filter an array of objects based on a condition while also filtering out unspecified keys.
|
||||
Filters an array of objects based on a condition while also filtering out unspecified keys.
|
||||
|
||||
- Use `Array.prototype.filter()` to filter the array based on the predicate `fn` so that it returns the objects for which the condition returned a truthy value.
|
||||
- On the filtered array, use `Array.prototype.map()` to return the new object using `Array.prototype.reduce()` to filter out the keys which were not supplied as the `keys` argument.
|
||||
- On the filtered array, use `Array.prototype.map()` to return the new object.
|
||||
- Use `Array.prototype.reduce()` to filter out the keys which were not supplied as the `keys` argument.
|
||||
|
||||
```js
|
||||
const reducedFilter = (data, keys, fn) =>
|
||||
@ -31,6 +32,6 @@ const data = [
|
||||
age: 50
|
||||
}
|
||||
];
|
||||
|
||||
reducedFilter(data, ['id', 'name'], item => item.age > 24); // [{ id: 2, name: 'mike'}]
|
||||
reducedFilter(data, ['id', 'name'], item => item.age > 24);
|
||||
// [{ id: 2, name: 'mike'}]
|
||||
```
|
||||
|
||||
@ -5,7 +5,7 @@ tags: array,beginner
|
||||
|
||||
Filters an array's values based on a predicate function, returning only values for which the predicate function returns `false`.
|
||||
|
||||
- Use `Array.prototype.filter()` in combination with the predicate function, `pred`, to return only the values for which `pred()` returns `false`.
|
||||
- Use `Array.prototype.filter()` in combination with the predicate function, `pred`, to return only the values for which it returns `false`.
|
||||
|
||||
```js
|
||||
const reject = (pred, array) => array.filter((...args) => !pred(...args));
|
||||
@ -13,5 +13,6 @@ const reject = (pred, array) => array.filter((...args) => !pred(...args));
|
||||
|
||||
```js
|
||||
reject(x => x % 2 === 0, [1, 2, 3, 4, 5]); // [1, 3, 5]
|
||||
reject(word => word.length > 4, ['Apple', 'Pear', 'Kiwi', 'Banana']); // ['Pear', 'Kiwi']
|
||||
reject(word => word.length > 4, ['Apple', 'Pear', 'Kiwi', 'Banana']);
|
||||
// ['Pear', 'Kiwi']
|
||||
```
|
||||
|
||||
@ -5,8 +5,9 @@ tags: array,intermediate
|
||||
|
||||
Mutates an array by removing elements for which the given function returns `false`.
|
||||
|
||||
- Use `Array.prototype.filter()` to find array elements that return truthy values and `Array.prototype.reduce()` to remove elements using `Array.prototype.splice()`.
|
||||
- The `func` is invoked with three arguments (`value, index, array`).
|
||||
- Use `Array.prototype.filter()` to find array elements that return truthy values.
|
||||
- Use `Array.prototype.reduce()` to remove elements using `Array.prototype.splice()`.
|
||||
- The callback function is invoked with three arguments (value, index, array).
|
||||
|
||||
```js
|
||||
|
||||
|
||||
@ -9,7 +9,8 @@ Removes accents from strings.
|
||||
- Use `String.prototype.replace()` to replace diacritical marks in the given Unicode range by empty strings.
|
||||
|
||||
```js
|
||||
const removeAccents = str => str.normalize('NFD').replace(/[\u0300-\u036f]/g, '');
|
||||
const removeAccents = str =>
|
||||
str.normalize('NFD').replace(/[\u0300-\u036f]/g, '');
|
||||
```
|
||||
|
||||
```js
|
||||
|
||||
Reference in New Issue
Block a user