Avoid confusing prototype methods for static methods
Correct: `Array.from()` (it’s a static method) Incorrect: `Array.join()` (doesn’t exist; it’s a prototype method) This patch uses the common `#` syntax to denote `.prototype.`.
This commit is contained in:
@ -52,7 +52,7 @@ Here's what you can do to help:
|
|||||||
|
|
||||||
### Additional guidelines and conventions regarding snippets
|
### Additional guidelines and conventions regarding snippets
|
||||||
|
|
||||||
- When describing snippets, refer to methods, using their full name. For example, use `Array.reduce()`, instead of `reduce()`.
|
- When describing snippets, refer to methods, using their full name. For example, use `Array.prototype.reduce()`, instead of `reduce()`.
|
||||||
- If your snippet contains argument with default parameters, explain what happens if they are omitted when calling the function and what the default case is.
|
- If your snippet contains argument with default parameters, explain what happens if they are omitted when calling the function and what the default case is.
|
||||||
- If your snippet uses recursion, explain the base cases.
|
- If your snippet uses recursion, explain the base cases.
|
||||||
- Always use `const functionName` for function definitions.
|
- Always use `const functionName` for function definitions.
|
||||||
@ -64,13 +64,13 @@ Here's what you can do to help:
|
|||||||
- `num` or `n` for a numeric value (usually as the snippet function's argument).
|
- `num` or `n` for a numeric value (usually as the snippet function's argument).
|
||||||
- `el` for DOM elements (usually as the snippet function's argument).
|
- `el` for DOM elements (usually as the snippet function's argument).
|
||||||
- `val` or `v` for value (usually when iterating a list, mapping, sorting etc.).
|
- `val` or `v` for value (usually when iterating a list, mapping, sorting etc.).
|
||||||
- `acc` for accumulators in `Array.reduce()`.
|
- `acc` for accumulators in `Array.prototype.reduce()`.
|
||||||
- `(a,b)` for the two values compared when using `Array.sort()`.
|
- `(a,b)` for the two values compared when using `Array.prototype.sort()`.
|
||||||
- `i` for indexes.
|
- `i` for indexes.
|
||||||
- `fn` for function arguments.
|
- `fn` for function arguments.
|
||||||
- `nums` for arrays of numbers.
|
- `nums` for arrays of numbers.
|
||||||
- Use `()` if your function takes no arguments.
|
- Use `()` if your function takes no arguments.
|
||||||
- Use `_` if an argument inside some function (e.g. `Array.reduce()`) is not used anywhere in your code.
|
- Use `_` if an argument inside some function (e.g. `Array.prototype.reduce()`) is not used anywhere in your code.
|
||||||
- Specify default parameters for arguments, if necessary. It is preferred to put default parameters last unless you have pretty good reason not to.
|
- Specify default parameters for arguments, if necessary. It is preferred to put default parameters last unless you have pretty good reason not to.
|
||||||
- If your snippet's function takes variadic arguments, use `...args` (although in certain cases, it might be needed to use a different name).
|
- If your snippet's function takes variadic arguments, use `...args` (although in certain cases, it might be needed to use a different name).
|
||||||
- If your snippet function's body is a single statement, omit the `return` keyword and use an expression instead.
|
- If your snippet function's body is a single statement, omit the `return` keyword and use an expression instead.
|
||||||
@ -79,7 +79,7 @@ Here's what you can do to help:
|
|||||||
- Always use single quotes for string literals. Use template literals, instead, if necessary.
|
- Always use single quotes for string literals. Use template literals, instead, if necessary.
|
||||||
- If your snippet's code is short enough (around 80 characters), you can make it a single-line function (although not mandatory). Otherwise, use multiple lines.
|
- If your snippet's code is short enough (around 80 characters), you can make it a single-line function (although not mandatory). Otherwise, use multiple lines.
|
||||||
- Prefer using `Array` methods whenever possible.
|
- Prefer using `Array` methods whenever possible.
|
||||||
- Prefer `Array.concat()` instead of `Array.push()` when working with `Array.reduce()`.
|
- Prefer `Array.prototype.concat()` instead of `Array.prototype.push()` when working with `Array.prototype.reduce()`.
|
||||||
- Use strict equality checking (`===` and `!==` instead of `==` and `!=`), unless you specifically have reason not to.
|
- Use strict equality checking (`===` and `!==` instead of `==` and `!=`), unless you specifically have reason not to.
|
||||||
- Prefer using the ternary operator (`condition ? trueResult : falseResult`) instead of `if else` statements whenever possible.
|
- Prefer using the ternary operator (`condition ? trueResult : falseResult`) instead of `if else` statements whenever possible.
|
||||||
- Avoid nesting ternary operators (but you can do it if you feel like you should).
|
- Avoid nesting ternary operators (but you can do it if you feel like you should).
|
||||||
|
|||||||
148
README.md
148
README.md
@ -20,7 +20,7 @@
|
|||||||
#### Related projects
|
#### Related projects
|
||||||
|
|
||||||
- [30 Seconds of CSS](https://30-seconds.github.io/30-seconds-of-css/)
|
- [30 Seconds of CSS](https://30-seconds.github.io/30-seconds-of-css/)
|
||||||
- [30 Seconds of Interviews](https://30secondsofinterviews.org/)
|
- [30 Seconds of Interviews](https://30secondsofinterviews.org/)
|
||||||
- [30 Seconds of Python](https://github.com/kriadmin/30-seconds-of-python-code) *(unofficial)*
|
- [30 Seconds of Python](https://github.com/kriadmin/30-seconds-of-python-code) *(unofficial)*
|
||||||
- [30 Seconds of PHP](https://github.com/appzcoder/30-seconds-of-php-code) *(unofficial)*
|
- [30 Seconds of PHP](https://github.com/appzcoder/30-seconds-of-php-code) *(unofficial)*
|
||||||
|
|
||||||
@ -521,12 +521,12 @@ const firstTwoMax = ary(Math.max, 2);
|
|||||||
|
|
||||||
<br>[⬆ Back to top](#table-of-contents)
|
<br>[⬆ Back to top](#table-of-contents)
|
||||||
|
|
||||||
### call
|
### call
|
||||||
|
|
||||||
Given a key and a set of arguments, call them when given a context. Primarily useful in composition.
|
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
|
```js
|
||||||
const call = (key, ...args) => context => context[key](...args);
|
const call = (key, ...args) => context => context[key](...args);
|
||||||
```
|
```
|
||||||
@ -542,18 +542,18 @@ const map = call.bind(null, 'map');
|
|||||||
Promise.resolve([1, 2, 3])
|
Promise.resolve([1, 2, 3])
|
||||||
.then(map(x => 2 * x))
|
.then(map(x => 2 * x))
|
||||||
.then(console.log); //[ 2, 4, 6 ]
|
.then(console.log); //[ 2, 4, 6 ]
|
||||||
```
|
```
|
||||||
|
|
||||||
</details>
|
</details>
|
||||||
|
|
||||||
<br>[⬆ Back to top](#table-of-contents)
|
<br>[⬆ Back to top](#table-of-contents)
|
||||||
|
|
||||||
### collectInto
|
### collectInto
|
||||||
|
|
||||||
Changes a function that accepts an array into a variadic function.
|
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
|
```js
|
||||||
const collectInto = fn => (...args) => fn(args);
|
const collectInto = fn => (...args) => fn(args);
|
||||||
```
|
```
|
||||||
@ -567,18 +567,18 @@ let p1 = Promise.resolve(1);
|
|||||||
let p2 = Promise.resolve(2);
|
let p2 = Promise.resolve(2);
|
||||||
let p3 = new Promise(resolve => setTimeout(resolve, 2000, 3));
|
let p3 = new Promise(resolve => setTimeout(resolve, 2000, 3));
|
||||||
Pall(p1, p2, p3).then(console.log); // [1, 2, 3] (after about 2 seconds)
|
Pall(p1, p2, p3).then(console.log); // [1, 2, 3] (after about 2 seconds)
|
||||||
```
|
```
|
||||||
|
|
||||||
</details>
|
</details>
|
||||||
|
|
||||||
<br>[⬆ Back to top](#table-of-contents)
|
<br>[⬆ Back to top](#table-of-contents)
|
||||||
|
|
||||||
### flip
|
### flip
|
||||||
|
|
||||||
Flip takes a function as an argument, then makes the first argument the last.
|
Flip takes a function as an argument, then makes the first argument the last.
|
||||||
|
|
||||||
Return a closure that takes variadic inputs, and splices the last argument to make it the first argument before applying the rest.
|
Return a closure that takes variadic inputs, and splices the last argument to make it the first argument before applying the rest.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const flip = fn => (first, ...rest) => fn(...rest, first);
|
const flip = fn => (first, ...rest) => fn(...rest, first);
|
||||||
```
|
```
|
||||||
@ -594,7 +594,7 @@ let mergePerson = mergeFrom.bind(null, a);
|
|||||||
mergePerson(b); // == b
|
mergePerson(b); // == b
|
||||||
b = {};
|
b = {};
|
||||||
Object.assign(b, a); // == b
|
Object.assign(b, a); // == b
|
||||||
```
|
```
|
||||||
|
|
||||||
</details>
|
</details>
|
||||||
|
|
||||||
@ -757,12 +757,12 @@ rearged('b', 'c', 'a'); // ['a', 'b', 'c']
|
|||||||
|
|
||||||
<br>[⬆ Back to top](#table-of-contents)
|
<br>[⬆ Back to top](#table-of-contents)
|
||||||
|
|
||||||
### spreadOver
|
### spreadOver
|
||||||
|
|
||||||
Takes a variadic function and returns a closure that accepts an array of arguments to map to the inputs of the function.
|
Takes a variadic function and returns a closure that accepts an array of arguments to map to the inputs of the function.
|
||||||
|
|
||||||
Use closures and the spread operator (`...`) to map the array of arguments to the inputs of the function.
|
Use closures and the spread operator (`...`) to map the array of arguments to the inputs of the function.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const spreadOver = fn => argsArr => fn(...argsArr);
|
const spreadOver = fn => argsArr => fn(...argsArr);
|
||||||
```
|
```
|
||||||
@ -773,7 +773,7 @@ const spreadOver = fn => argsArr => fn(...argsArr);
|
|||||||
```js
|
```js
|
||||||
const arrayMax = spreadOver(Math.max);
|
const arrayMax = spreadOver(Math.max);
|
||||||
arrayMax([1, 2, 3]); // 3
|
arrayMax([1, 2, 3]); // 3
|
||||||
```
|
```
|
||||||
|
|
||||||
</details>
|
</details>
|
||||||
|
|
||||||
@ -1448,7 +1448,7 @@ head([1, 2, 3]); // 1
|
|||||||
|
|
||||||
### indexOfAll
|
### indexOfAll
|
||||||
|
|
||||||
Returns all indices of `val` in an array.
|
Returns all indices of `val` in an array.
|
||||||
If `val` never occurs, returns `[]`.
|
If `val` never occurs, returns `[]`.
|
||||||
|
|
||||||
Use `Array.reduce()` to loop over elements and store indices for matching elements.
|
Use `Array.reduce()` to loop over elements and store indices for matching elements.
|
||||||
@ -1718,7 +1718,7 @@ isSorted([4, 3, 5]); // 0
|
|||||||
|
|
||||||
### join
|
### join
|
||||||
|
|
||||||
Joins all elements of an array into a string and returns this string.
|
Joins all elements of an array into a string and returns this string.
|
||||||
Uses a separator and an end separator.
|
Uses a separator and an end separator.
|
||||||
|
|
||||||
Use `Array.reduce()` to combine elements into a string.
|
Use `Array.reduce()` to combine elements into a string.
|
||||||
@ -1812,7 +1812,7 @@ Takes any number of iterable objects or objects with a `length` property and ret
|
|||||||
If multiple objects have the same length, the first one will be returned.
|
If multiple objects have the same length, the first one will be returned.
|
||||||
Returns `undefined` if no arguments are provided.
|
Returns `undefined` if no arguments are provided.
|
||||||
|
|
||||||
Use `Array.reduce()`, comparing the `length` of objects to find the longest one.
|
Use `Array.reduce()`, comparing the `length` of objects to find the longest one.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const longestItem = (val, ...vals) =>
|
const longestItem = (val, ...vals) =>
|
||||||
@ -1861,7 +1861,7 @@ squareIt([1, 2, 3]); // { 1: 1, 2: 4, 3: 9 }
|
|||||||
|
|
||||||
### maxN
|
### maxN
|
||||||
|
|
||||||
Returns the `n` maximum elements from the provided array.
|
Returns the `n` maximum elements from the provided array.
|
||||||
If `n` is greater than or equal to the provided array's length, then return the original array (sorted in descending order).
|
If `n` is greater than or equal to the provided array's length, then return the original array (sorted in descending order).
|
||||||
|
|
||||||
Use `Array.sort()` combined with the spread operator (`...`) to create a shallow clone of the array and sort it in descending order.
|
Use `Array.sort()` combined with the spread operator (`...`) to create a shallow clone of the array and sort it in descending order.
|
||||||
@ -1886,7 +1886,7 @@ maxN([1, 2, 3], 2); // [3,2]
|
|||||||
|
|
||||||
### minN
|
### minN
|
||||||
|
|
||||||
Returns the `n` minimum elements from the provided array.
|
Returns the `n` minimum elements from the provided array.
|
||||||
If `n` is greater than or equal to the provided array's length, then return the original array (sorted in ascending order).
|
If `n` is greater than or equal to the provided array's length, then return the original array (sorted in ascending order).
|
||||||
|
|
||||||
Use `Array.sort()` combined with the spread operator (`...`) to create a shallow clone of the array and sort it in ascending order.
|
Use `Array.sort()` combined with the spread operator (`...`) to create a shallow clone of the array and sort it in ascending order.
|
||||||
@ -2175,7 +2175,7 @@ pullBy(myArray, [{ x: 1 }, { x: 3 }], o => o.x); // myArray = [{ x: 2 }]
|
|||||||
|
|
||||||
Filter an array of objects based on a condition while also filtering out unspecified keys.
|
Filter an array of objects based on a condition while also filtering out unspecified keys.
|
||||||
|
|
||||||
Use `Array.filter()` to filter the array based on the predicate `fn` so that it returns the objects for which the condition returned a truthy value.
|
Use `Array.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.map()` to return the new object using `Array.reduce()` to filter out the keys which were not supplied as the `keys` argument.
|
On the filtered array, use `Array.map()` to return the new object using `Array.reduce()` to filter out the keys which were not supplied as the `keys` argument.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
@ -2558,10 +2558,10 @@ sortedLastIndexBy([{ x: 4 }, { x: 5 }], { x: 4 }, o => o.x); // 1
|
|||||||
|
|
||||||
### stableSort 
|
### stableSort 
|
||||||
|
|
||||||
Performs stable sorting of an array, preserving the initial indexes of items when their values are the same.
|
Performs stable sorting of an array, preserving the initial indexes of items when their values are the same.
|
||||||
Does not mutate the original array, but returns a new array instead.
|
Does not mutate the original array, but returns a new array instead.
|
||||||
|
|
||||||
Use `Array.map()` to pair each element of the input array with its corresponding index.
|
Use `Array.map()` to pair each element of the input array with its corresponding index.
|
||||||
Use `Array.sort()` and a `compare` function to sort the list, preserving their initial order if the items compared are equal.
|
Use `Array.sort()` and a `compare` function to sort the list, preserving their initial order if the items compared are equal.
|
||||||
Use `Array.map()` to convert back to the initial array items.
|
Use `Array.map()` to convert back to the initial array items.
|
||||||
|
|
||||||
@ -3253,7 +3253,7 @@ bottomVisible(); // true
|
|||||||
|
|
||||||
⚠️ **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).
|
⚠️ **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).
|
||||||
|
|
||||||
Copy a string to the clipboard.
|
Copy a string to the clipboard.
|
||||||
Only works as a result of user action (i.e. inside a `click` event listener).
|
Only works as a result of user action (i.e. inside a `click` event listener).
|
||||||
|
|
||||||
Create a new `<textarea>` element, fill it with the supplied data and add it to the HTML document.
|
Create a new `<textarea>` element, fill it with the supplied data and add it to the HTML document.
|
||||||
@ -3330,11 +3330,11 @@ counter('#my-id', 1, 1000, 5, 2000); // Creates a 2-second timer for the element
|
|||||||
|
|
||||||
### createElement
|
### createElement
|
||||||
|
|
||||||
Creates an element from a string (without appending it to the document).
|
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.
|
If the given string contains multiple elements, only the first one will be returned.
|
||||||
|
|
||||||
Use `document.createElement()` to create a new element.
|
Use `document.createElement()` to create a new element.
|
||||||
Set its `innerHTML` to the string supplied as the argument.
|
Set its `innerHTML` to the string supplied as the argument.
|
||||||
Use `ParentNode.firstElementChild` to return the element version of the string.
|
Use `ParentNode.firstElementChild` to return the element version of the string.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
@ -3634,7 +3634,7 @@ hide(document.querySelectorAll('img')); // Hides all <img> elements on the page
|
|||||||
|
|
||||||
Redirects the page to HTTPS if its currently in HTTP. Also, pressing the back button doesn't take it back to the HTTP page as its replaced in the history.
|
Redirects the page to HTTPS if its currently in HTTP. Also, pressing the back button doesn't take it back to the HTTP page as its replaced in the history.
|
||||||
|
|
||||||
Use `location.protocol` to get the protocol currently being used. If it's not HTTPS, use `location.replace()` to replace the existing page with the HTTPS version of the page. Use `location.href` to get the full address, split it with `String.split()` and remove the protocol part of the URL.
|
Use `location.protocol` to get the protocol currently being used. If it's not HTTPS, use `location.replace()` to replace the existing page with the HTTPS version of the page. Use `location.href` to get the full address, split it with `String.split()` and remove the protocol part of the URL.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const httpsRedirect = () => {
|
const httpsRedirect = () => {
|
||||||
@ -3782,7 +3782,7 @@ obs.disconnect(); // Disconnects the observer and stops logging mutations on the
|
|||||||
|
|
||||||
Removes an event listener from an element.
|
Removes an event listener from an element.
|
||||||
|
|
||||||
Use `EventTarget.removeEventListener()` to remove an event listener from an element.
|
Use `EventTarget.removeEventListener()` to remove an event listener from an element.
|
||||||
Omit the fourth argument `opts` to use `false` or specify it based on the options used when the event listener was added.
|
Omit the fourth argument `opts` to use `false` or specify it based on the options used when the event listener was added.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
@ -3836,7 +3836,7 @@ on(document.body, 'click', fn, { options: true }); // use capturing instead of b
|
|||||||
|
|
||||||
Run the callback whenever the user input type changes (`mouse` or `touch`). Useful for enabling/disabling code depending on the input device. This process is dynamic and works with hybrid devices (e.g. touchscreen laptops).
|
Run the callback whenever the user input type changes (`mouse` or `touch`). Useful for enabling/disabling code depending on the input device. This process is dynamic and works with hybrid devices (e.g. touchscreen laptops).
|
||||||
|
|
||||||
Use two event listeners. Assume `mouse` input initially and bind a `touchstart` event listener to the document.
|
Use two event listeners. Assume `mouse` input initially and bind a `touchstart` event listener to the document.
|
||||||
On `touchstart`, add a `mousemove` event listener to listen for two consecutive `mousemove` events firing within 20ms, using `performance.now()`.
|
On `touchstart`, add a `mousemove` event listener to listen for two consecutive `mousemove` events firing within 20ms, using `performance.now()`.
|
||||||
Run the callback with the input type as an argument in either of these situations.
|
Run the callback with the input type as an argument in either of these situations.
|
||||||
|
|
||||||
@ -3874,7 +3874,7 @@ onUserInputChange(type => {
|
|||||||
|
|
||||||
Returns the prefixed version (if necessary) of a CSS property that the browser supports.
|
Returns the prefixed version (if necessary) of a CSS property that the browser supports.
|
||||||
|
|
||||||
Use `Array.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 `Array.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.charAt()` and `String.toUpperCase()` to capitalize the property, which will be appended to the vendor prefix string.
|
Use `String.charAt()` and `String.toUpperCase()` to capitalize the property, which will be appended to the vendor prefix string.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
@ -3903,9 +3903,9 @@ prefix('appearance'); // 'appearance' on a supported browser, otherwise 'webkitA
|
|||||||
|
|
||||||
Invokes the provided callback on each animation frame.
|
Invokes the provided callback on each animation frame.
|
||||||
|
|
||||||
Use recursion.
|
Use recursion.
|
||||||
Provided that `running` is `true`, continue invoking `window.requestAnimationFrame()` which invokes the provided callback.
|
Provided that `running` is `true`, continue invoking `window.requestAnimationFrame()` which invokes the provided callback.
|
||||||
Return an object with two methods `start` and `stop` to allow manual control of the recording.
|
Return an object with two methods `start` and `stop` to allow manual control of the recording.
|
||||||
Omit the second argument, `autoStart`, to implicitly call `start` when the function is invoked.
|
Omit the second argument, `autoStart`, to implicitly call `start` when the function is invoked.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
@ -4099,7 +4099,7 @@ show(...document.querySelectorAll('img')); // Shows all <img> elements on the pa
|
|||||||
|
|
||||||
Smoothly scrolls the element on which it's called into the visible area of the browser window.
|
Smoothly scrolls the element on which it's called into the visible area of the browser window.
|
||||||
|
|
||||||
Use `.scrollIntoView` method to scroll the element.
|
Use `.scrollIntoView` method to scroll the element.
|
||||||
Pass `{ behavior: 'smooth' }` to `.scrollIntoView` so it scrolls smoothly.
|
Pass `{ behavior: 'smooth' }` to `.scrollIntoView` so it scrolls smoothly.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
@ -4678,11 +4678,11 @@ functionName(Math.max); // max (logged in debug channel of console)
|
|||||||
|
|
||||||
### hz
|
### hz
|
||||||
|
|
||||||
Returns the number of times a function executed per second.
|
Returns the number of times a function executed per second.
|
||||||
`hz` is the unit for `hertz`, the unit of frequency defined as one cycle per second.
|
`hz` is the unit for `hertz`, the unit of frequency defined as one cycle per second.
|
||||||
|
|
||||||
Use `performance.now()` to get the difference in milliseconds before and after the iteration loop to calculate the time elapsed executing the function `iterations` times.
|
Use `performance.now()` to get the difference in milliseconds before and after the iteration loop to calculate the time elapsed executing the function `iterations` times.
|
||||||
Return the number of cycles per second by converting milliseconds to seconds and dividing it by the time elapsed.
|
Return the number of cycles per second by converting milliseconds to seconds and dividing it by the time elapsed.
|
||||||
Omit the second argument, `iterations`, to use the default of 100 iterations.
|
Omit the second argument, `iterations`, to use the default of 100 iterations.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
@ -5036,7 +5036,7 @@ unfold(f, 10); // [-10, -20, -30, -40, -50]
|
|||||||
|
|
||||||
### when
|
### when
|
||||||
|
|
||||||
Tests a value, `x`, against a predicate function. If `true`, return `fn(x)`. Else, return `x`.
|
Tests a value, `x`, against a predicate function. If `true`, return `fn(x)`. Else, return `x`.
|
||||||
|
|
||||||
Return a function expecting a single value, `x`, that returns the appropriate value based on `pred`.
|
Return a function expecting a single value, `x`, that returns the appropriate value based on `pred`.
|
||||||
|
|
||||||
@ -5259,7 +5259,7 @@ The array should be ordered from best performer to worst performer (winner -> lo
|
|||||||
|
|
||||||
Use the exponent `**` operator and math operators to compute the expected score (chance of winning).
|
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.
|
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.
|
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.
|
Omit the second argument to use the default `kFactor` of 32.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
@ -6232,7 +6232,7 @@ console.log(arr); // ['line1', 'line2', 'line3']
|
|||||||
|
|
||||||
Converts a tilde path to an absolute path.
|
Converts a tilde path to an absolute path.
|
||||||
|
|
||||||
Use `String.replace()` with a regular expression and `OS.homedir()` to replace the `~` in the start of the path with the home directory.
|
Use `String.prototype.replace()` with a regular expression and `OS.homedir()` to replace the `~` in the start of the path with the home directory.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const untildify = str => str.replace(/^~($|\/|\\)/, `${require('os').homedir()}$1`);
|
const untildify = str => str.replace(/^~($|\/|\\)/, `${require('os').homedir()}$1`);
|
||||||
@ -6494,10 +6494,10 @@ findKey(
|
|||||||
|
|
||||||
### findLastKey
|
### findLastKey
|
||||||
|
|
||||||
Returns the last key that satisfies the provided testing function.
|
Returns the last key that satisfies the provided testing function.
|
||||||
Otherwise `undefined` is returned.
|
Otherwise `undefined` is returned.
|
||||||
|
|
||||||
Use `Object.keys(obj)` to get all the properties of the object, `Array.reverse()` to reverse their order and `Array.find()` to test the provided function for each key-value pair.
|
Use `Object.keys(obj)` to get all the properties of the object, `Array.reverse()` to reverse their order and `Array.find()` to test the provided function for each key-value pair.
|
||||||
The callback receives three arguments - the value, the key and the object.
|
The callback receives three arguments - the value, the key and the object.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
@ -6639,7 +6639,7 @@ functions(new Foo(), true); // ['a', 'b', 'c']
|
|||||||
|
|
||||||
Retrieve a set of properties indicated by the given selectors from an object.
|
Retrieve a set of properties indicated by the given selectors from an object.
|
||||||
|
|
||||||
Use `Array.map()` for each selector, `String.replace()` to replace square brackets with dots, `String.split('.')` to split each selector, `Array.filter()` to remove empty values and `Array.reduce()` to get the value indicated by it.
|
Use `Array.map()` for each selector, `String.prototype.replace()` to replace square brackets with dots, `String.split('.')` to split each selector, `Array.filter()` to remove empty values and `Array.reduce()` to get the value indicated by it.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const get = (from, ...selectors) =>
|
const get = (from, ...selectors) =>
|
||||||
@ -6876,9 +6876,9 @@ merge(object, other); // { a: [ { x: 2 }, { y: 4 }, { z: 3 } ], b: [ 1, 2, 3 ],
|
|||||||
Given a flat array of objects linked to one another, it will nest them recursively.
|
Given a flat array of objects linked to one another, it will nest them recursively.
|
||||||
Useful for nesting comments, such as the ones on reddit.com.
|
Useful for nesting comments, such as the ones on reddit.com.
|
||||||
|
|
||||||
Use recursion.
|
Use recursion.
|
||||||
Use `Array.filter()` to filter the items where the `id` matches the `link`, then `Array.map()` to map each one to a new object that has a `children` property which recursively nests the items based on which ones are children of the current item.
|
Use `Array.filter()` to filter the items where the `id` matches the `link`, then `Array.map()` to map each one to a new object that has a `children` property which recursively nests the items based on which ones are children of the current item.
|
||||||
Omit the second argument, `id`, to default to `null` which indicates the object is not linked to another one (i.e. it is a top level object).
|
Omit the second argument, `id`, to default to `null` which indicates the object is not linked to another one (i.e. it is a top level object).
|
||||||
Omit the third argument, `link`, to use `'parent_id'` as the default property which links the object to another one by its `id`.
|
Omit the third argument, `link`, to use `'parent_id'` as the default property which links the object to another one by its `id`.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
@ -7135,7 +7135,7 @@ const b = shallowClone(a); // a !== b
|
|||||||
|
|
||||||
Get size of arrays, objects or strings.
|
Get size of arrays, objects or strings.
|
||||||
|
|
||||||
Get type of `val` (`array`, `object` or `string`).
|
Get type of `val` (`array`, `object` or `string`).
|
||||||
Use `length` property for arrays.
|
Use `length` property for arrays.
|
||||||
Use `length` or `size` value if available or number of keys for objects.
|
Use `length` or `size` value if available or number of keys for objects.
|
||||||
Use `size` of a [`Blob` object](https://developer.mozilla.org/en-US/docs/Web/API/Blob) created from `val` for strings.
|
Use `size` of a [`Blob` object](https://developer.mozilla.org/en-US/docs/Web/API/Blob) created from `val` for strings.
|
||||||
@ -7308,7 +7308,7 @@ capitalize('fooBar', true); // 'Foobar'
|
|||||||
|
|
||||||
Capitalizes the first letter of every word in a string.
|
Capitalizes the first letter of every word in a string.
|
||||||
|
|
||||||
Use `String.replace()` to match the first character of each word and `String.toUpperCase()` to capitalize it.
|
Use `String.prototype.replace()` to match the first character of each word and `String.toUpperCase()` to capitalize it.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const capitalizeEveryWord = str => str.replace(/\b[a-z]/g, char => char.toUpperCase());
|
const capitalizeEveryWord = str => str.replace(/\b[a-z]/g, char => char.toUpperCase());
|
||||||
@ -7418,7 +7418,7 @@ decapitalize('FooBar', true); // 'fOOBAR'
|
|||||||
|
|
||||||
Escapes a string for use in HTML.
|
Escapes a string for use in HTML.
|
||||||
|
|
||||||
Use `String.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
|
```js
|
||||||
const escapeHTML = str =>
|
const escapeHTML = str =>
|
||||||
@ -7450,7 +7450,7 @@ escapeHTML('<a href="#">Me & you</a>'); // '<a href="#">Me &
|
|||||||
|
|
||||||
Escapes a string to use in a regular expression.
|
Escapes a string to use in a regular expression.
|
||||||
|
|
||||||
Use `String.replace()` to escape special characters.
|
Use `String.prototype.replace()` to escape special characters.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const escapeRegExp = str => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
const escapeRegExp = str => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||||
@ -7471,7 +7471,7 @@ escapeRegExp('(test)'); // \\(test\\)
|
|||||||
|
|
||||||
Converts a string from camelcase.
|
Converts a string from camelcase.
|
||||||
|
|
||||||
Use `String.replace()` to remove underscores, hyphens, and spaces and convert words to camelcase.
|
Use `String.prototype.replace()` to remove underscores, hyphens, and spaces and convert words to camelcase.
|
||||||
Omit the second argument to use a default `separator` of `_`.
|
Omit the second argument to use a default `separator` of `_`.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
@ -7545,7 +7545,7 @@ isAbsoluteURL('/foo/bar'); // false
|
|||||||
|
|
||||||
Checks if a string is an anagram of another string (case-insensitive, ignores spaces, punctuation and special characters).
|
Checks if a string is an anagram of another string (case-insensitive, ignores spaces, punctuation and special characters).
|
||||||
|
|
||||||
Use `String.toLowerCase()`, `String.replace()` with an appropriate regular expression to remove unnecessary characters, `String.split('')`, `Array.sort()` and `Array.join('')` on both strings to normalize them, then check if their normalized forms are equal.
|
Use `String.toLowerCase()`, `String.prototype.replace()` with an appropriate regular expression to remove unnecessary characters, `String.split('')`, `Array.sort()` and `Array.join('')` on both strings to normalize them, then check if their normalized forms are equal.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const isAnagram = (str1, str2) => {
|
const isAnagram = (str1, str2) => {
|
||||||
@ -7699,7 +7699,7 @@ pad('foobar', 3); // 'foobar'
|
|||||||
|
|
||||||
Returns `true` if the given string is a palindrome, `false` otherwise.
|
Returns `true` if the given string is a palindrome, `false` otherwise.
|
||||||
|
|
||||||
Convert string `String.toLowerCase()` and use `String.replace()` to remove non-alphanumeric characters from it.
|
Convert string `String.toLowerCase()` and use `String.prototype.replace()` to remove non-alphanumeric characters from it.
|
||||||
Then, use the spread operator (`...`) to split string into individual characters, `Array.reverse()`, `String.join('')` and compare to the original, unreversed string, after converting it `String.tolowerCase()`.
|
Then, use the spread operator (`...`) to split string into individual characters, `Array.reverse()`, `String.join('')` and compare to the original, unreversed string, after converting it `String.tolowerCase()`.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
@ -8016,7 +8016,7 @@ truncateString('boomerang', 7); // 'boom...'
|
|||||||
|
|
||||||
Unescapes escaped HTML characters.
|
Unescapes escaped HTML characters.
|
||||||
|
|
||||||
Use `String.replace()` with a regex that matches the characters that need to be unescaped, using a callback function to replace each escaped character instance with its associated unescaped character using a dictionary (object).
|
Use `String.prototype.replace()` with a regex that matches the characters that need to be unescaped, using a callback function to replace each escaped character instance with its associated unescaped character using a dictionary (object).
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const unescapeHTML = str =>
|
const unescapeHTML = str =>
|
||||||
@ -8048,7 +8048,7 @@ unescapeHTML('<a href="#">Me & you</a>'); // '<a href=
|
|||||||
|
|
||||||
Joins all given URL segments together, then normalizes the resulting URL.
|
Joins all given URL segments together, then normalizes the resulting URL.
|
||||||
|
|
||||||
Use `String.join('/')` to combine URL segments, then a series of `String.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.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
|
```js
|
||||||
const URLJoin = (...args) =>
|
const URLJoin = (...args) =>
|
||||||
@ -8322,7 +8322,7 @@ isNumber(1); // true
|
|||||||
|
|
||||||
Returns a boolean determining if the passed value is an object or not.
|
Returns a boolean determining if the passed value is an object or not.
|
||||||
|
|
||||||
Uses the `Object` constructor to create an object wrapper for the given value.
|
Uses the `Object` constructor to create an object wrapper for the given value.
|
||||||
If the value is `null` or `undefined`, create and return an empty object. Οtherwise, return an object of a type that corresponds to the given value.
|
If the value is `null` or `undefined`, create and return an empty object. Οtherwise, return an object of a type that corresponds to the given value.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
@ -8757,7 +8757,7 @@ const httpGet = (url, callback, err = console.error) => {
|
|||||||
httpGet(
|
httpGet(
|
||||||
'https://jsonplaceholder.typicode.com/posts/1',
|
'https://jsonplaceholder.typicode.com/posts/1',
|
||||||
console.log
|
console.log
|
||||||
); /*
|
); /*
|
||||||
Logs: {
|
Logs: {
|
||||||
"userId": 1,
|
"userId": 1,
|
||||||
"id": 1,
|
"id": 1,
|
||||||
@ -8835,8 +8835,8 @@ Logs: {
|
|||||||
|
|
||||||
Determines if the current runtime environment is a browser so that front-end modules can run on the server (Node) without throwing errors.
|
Determines if the current runtime environment is a browser so that front-end modules can run on the server (Node) without throwing errors.
|
||||||
|
|
||||||
Use `Array.includes()` on the `typeof` values of both `window` and `document` (globals usually only available in a browser environment unless they were explicitly defined), which will return `true` if one of them is `undefined`.
|
Use `Array.includes()` on the `typeof` values of both `window` and `document` (globals usually only available in a browser environment unless they were explicitly defined), which will return `true` if one of them is `undefined`.
|
||||||
`typeof` allows globals to be checked for existence without throwing a `ReferenceError`.
|
`typeof` allows globals to be checked for existence without throwing a `ReferenceError`.
|
||||||
If both of them are not `undefined`, then the current environment is assumed to be a browser.
|
If both of them are not `undefined`, then the current environment is assumed to be a browser.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
@ -8860,7 +8860,7 @@ isBrowser(); // false (Node)
|
|||||||
Returns the index of the function in an array of functions which executed the fastest.
|
Returns the index of the function in an array of functions which executed the fastest.
|
||||||
|
|
||||||
Use `Array.map()` to generate an array where each value is the total time taken to execute the function after `iterations` times. Use the difference in `performance.now()` values before and after to get the total time in milliseconds to a high degree of accuracy.
|
Use `Array.map()` to generate an array where each value is the total time taken to execute the function after `iterations` times. Use the difference in `performance.now()` values before and after to get the total time in milliseconds to a high degree of accuracy.
|
||||||
Use `Math.min()` to find the minimum execution time, and return the index of that shortest time which corresponds to the index of the most performant function.
|
Use `Math.min()` to find the minimum execution time, and return the index of that shortest time which corresponds to the index of the most performant function.
|
||||||
Omit the second argument, `iterations`, to use a default of 10,000 iterations. The more iterations, the more reliable the result but the longer it will take.
|
Omit the second argument, `iterations`, to use a default of 10,000 iterations. The more iterations, the more reliable the result but the longer it will take.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@ -5,7 +5,7 @@
|
|||||||
"type": "snippet",
|
"type": "snippet",
|
||||||
"attributes": {
|
"attributes": {
|
||||||
"fileName": "binarySearch.md",
|
"fileName": "binarySearch.md",
|
||||||
"text": "Use recursion. Similar to `Array.indexOf()` that finds the index of a value within an array.\nThe difference being this operation only works with sorted arrays which offers a major performance boost due to it's logarithmic nature when compared to a linear search or `Array.indexOf()`.\n\nSearch a sorted array by repeatedly dividing the search interval in half.\nBegin with an interval covering the whole array.\nIf the value of the search is less than the item in the middle of the interval, recurse into the lower half. Otherwise recurse into the upper half.\nRepeatedly recurse until the value is found which is the mid or you've recursed to a point that is greater than the length which means the value doesn't exist and return `-1`.",
|
"text": "Use recursion. Similar to `Array.prototype.indexOf()` that finds the index of a value within an array.\nThe difference being this operation only works with sorted arrays which offers a major performance boost due to it's logarithmic nature when compared to a linear search or `Array.prototype.indexOf()`.\n\nSearch a sorted array by repeatedly dividing the search interval in half.\nBegin with an interval covering the whole array.\nIf the value of the search is less than the item in the middle of the interval, recurse into the lower half. Otherwise recurse into the upper half.\nRepeatedly recurse until the value is found which is the mid or you've recursed to a point that is greater than the length which means the value doesn't exist and return `-1`.",
|
||||||
"codeBlocks": [
|
"codeBlocks": [
|
||||||
"const binarySearch = (arr, val, start = 0, end = arr.length - 1) => {\n if (start > end) return -1;\n const mid = Math.floor((start + end) / 2);\n if (arr[mid] > val) return binarySearch(arr, val, start, mid - 1);\n if (arr[mid] < val) return binarySearch(arr, val, mid + 1, end);\n return mid;\n};",
|
"const binarySearch = (arr, val, start = 0, end = arr.length - 1) => {\n if (start > end) return -1;\n const mid = Math.floor((start + end) / 2);\n if (arr[mid] > val) return binarySearch(arr, val, start, mid - 1);\n if (arr[mid] < val) return binarySearch(arr, val, mid + 1, end);\n return mid;\n};",
|
||||||
"binarySearch([1, 4, 6, 7, 12, 13, 15, 18, 19, 20, 22, 24], 6); // 2\nbinarySearch([1, 4, 6, 7, 12, 13, 15, 18, 19, 20, 22, 24], 21); // -1"
|
"binarySearch([1, 4, 6, 7, 12, 13, 15, 18, 19, 20, 22, 24], 6); // 2\nbinarySearch([1, 4, 6, 7, 12, 13, 15, 18, 19, 20, 22, 24], 21); // -1"
|
||||||
@ -73,7 +73,7 @@
|
|||||||
"type": "snippet",
|
"type": "snippet",
|
||||||
"attributes": {
|
"attributes": {
|
||||||
"fileName": "factors.md",
|
"fileName": "factors.md",
|
||||||
"text": "Returns the array of factors of the given `num`. \nIf the second argument is set to `true` returns only the prime factors of `num`.\nIf `num` is `1` or `0` returns an empty array.\nIf `num` is less than `0` returns all the factors of `-int` together with their additive inverses.\n\nUse `Array.from()`, `Array.map()` and `Array.filter()` to find all the factors of `num`.\nIf given `num` is negative, use `Array.reduce()` to add the additive inverses to the array.\nReturn all results if `primes` is `false`, else determine and return only the prime factors using `isPrime` and `Array.filter()`.\nOmit the second argument, `primes`, to return prime and non-prime factors by default.\n\n**Note**:- _Negative numbers are not considered prime._",
|
"text": "Returns the array of factors of the given `num`. \nIf the second argument is set to `true` returns only the prime factors of `num`.\nIf `num` is `1` or `0` returns an empty array.\nIf `num` is less than `0` returns all the factors of `-int` together with their additive inverses.\n\nUse `Array.from()`, `Array.prototype.map()` and `Array.prototype.filter()` to find all the factors of `num`.\nIf given `num` is negative, use `Array.prototype.reduce()` to add the additive inverses to the array.\nReturn all results if `primes` is `false`, else determine and return only the prime factors using `isPrime` and `Array.prototype.filter()`.\nOmit the second argument, `primes`, to return prime and non-prime factors by default.\n\n**Note**:- _Negative numbers are not considered prime._",
|
||||||
"codeBlocks": [
|
"codeBlocks": [
|
||||||
"const factors = (num, primes = false) => {\n const isPrime = num => {\n const boundary = Math.floor(Math.sqrt(num));\n for (var i = 2; i <= boundary; i++) if (num % i === 0) return false;\n return num >= 2;\n };\n const isNeg = num < 0;\n num = isNeg ? -num : num;\n let array = Array.from({ length: num - 1 })\n .map((val, i) => (num % (i + 2) === 0 ? i + 2 : false))\n .filter(val => val);\n if (isNeg)\n array = array.reduce((acc, val) => {\n acc.push(val);\n acc.push(-val);\n return acc;\n }, []);\n return primes ? array.filter(isPrime) : array;\n};",
|
"const factors = (num, primes = false) => {\n const isPrime = num => {\n const boundary = Math.floor(Math.sqrt(num));\n for (var i = 2; i <= boundary; i++) if (num % i === 0) return false;\n return num >= 2;\n };\n const isNeg = num < 0;\n num = isNeg ? -num : num;\n let array = Array.from({ length: num - 1 })\n .map((val, i) => (num % (i + 2) === 0 ? i + 2 : false))\n .filter(val => val);\n if (isNeg)\n array = array.reduce((acc, val) => {\n acc.push(val);\n acc.push(-val);\n return acc;\n }, []);\n return primes ? array.filter(isPrime) : array;\n};",
|
||||||
"factors(12); // [2,3,4,6,12]\nfactors(12, true); // [2,3]\nfactors(-12); // [2, -2, 3, -3, 4, -4, 6, -6, 12, -12]\nfactors(-12, true); // [2,3]"
|
"factors(12); // [2,3,4,6,12]\nfactors(12, true); // [2,3]\nfactors(-12); // [2, -2, 3, -3, 4, -4, 6, -6, 12, -12]\nfactors(-12, true); // [2,3]"
|
||||||
@ -107,7 +107,7 @@
|
|||||||
"type": "snippet",
|
"type": "snippet",
|
||||||
"attributes": {
|
"attributes": {
|
||||||
"fileName": "fibonacciUntilNum.md",
|
"fileName": "fibonacciUntilNum.md",
|
||||||
"text": "Generates an array, containing the Fibonacci sequence, up until the nth term.\n\nCreate an empty array of the specific length, initializing the first two values (`0` and `1`).\nUse `Array.reduce()` to add values into the array, using the sum of the last two values, except for the first two.\nUses a mathematical formula to calculate the length of the array required.",
|
"text": "Generates an array, containing the Fibonacci sequence, up until the nth term.\n\nCreate an empty array of the specific length, initializing the first two values (`0` and `1`).\nUse `Array.prototype.reduce()` to add values into the array, using the sum of the last two values, except for the first two.\nUses a mathematical formula to calculate the length of the array required.",
|
||||||
"codeBlocks": [
|
"codeBlocks": [
|
||||||
"const fibonacciUntilNum = num => {\n let n = Math.ceil(Math.log(num * Math.sqrt(5) + 1 / 2) / Math.log((Math.sqrt(5) + 1) / 2));\n return Array.from({ length: n }).reduce(\n (acc, val, i) => acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : i),\n []\n );\n};",
|
"const fibonacciUntilNum = num => {\n let n = Math.ceil(Math.log(num * Math.sqrt(5) + 1 / 2) / Math.log((Math.sqrt(5) + 1) / 2));\n return Array.from({ length: n }).reduce(\n (acc, val, i) => acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : i),\n []\n );\n};",
|
||||||
"fibonacciUntilNum(10); // [ 0, 1, 1, 2, 3, 5, 8 ]"
|
"fibonacciUntilNum(10); // [ 0, 1, 1, 2, 3, 5, 8 ]"
|
||||||
@ -260,7 +260,7 @@
|
|||||||
"type": "snippet",
|
"type": "snippet",
|
||||||
"attributes": {
|
"attributes": {
|
||||||
"fileName": "quickSort.md",
|
"fileName": "quickSort.md",
|
||||||
"text": "QuickSort an Array (ascending sort by default).\n\nUse recursion. \nUse `Array.filter` and spread operator (`...`) to create an array that all elements with values less than the pivot come before the pivot, and all elements with values greater than the pivot come after it. \nIf the parameter `desc` is truthy, return array sorts in descending order.",
|
"text": "QuickSort an Array (ascending sort by default).\n\nUse recursion. \nUse `Array.prototype.filter` and spread operator (`...`) to create an array that all elements with values less than the pivot come before the pivot, and all elements with values greater than the pivot come after it. \nIf the parameter `desc` is truthy, return array sorts in descending order.",
|
||||||
"codeBlocks": [
|
"codeBlocks": [
|
||||||
"const quickSort = ([n, ...nums], desc) =>\n isNaN(n)\n ? []\n : [\n ...quickSort(nums.filter(v => (desc ? v > n : v <= n)), desc),\n n,\n ...quickSort(nums.filter(v => (!desc ? v > n : v <= n)), desc)\n ];",
|
"const quickSort = ([n, ...nums], desc) =>\n isNaN(n)\n ? []\n : [\n ...quickSort(nums.filter(v => (desc ? v > n : v <= n)), desc),\n n,\n ...quickSort(nums.filter(v => (!desc ? v > n : v <= n)), desc)\n ];",
|
||||||
"quickSort([4, 1, 3, 2]); // [1,2,3,4]\nquickSort([4, 1, 3, 2], true); // [4,3,2,1]"
|
"quickSort([4, 1, 3, 2]); // [1,2,3,4]\nquickSort([4, 1, 3, 2], true); // [4,3,2,1]"
|
||||||
@ -330,7 +330,7 @@
|
|||||||
"type": "snippet",
|
"type": "snippet",
|
||||||
"attributes": {
|
"attributes": {
|
||||||
"fileName": "removeVowels.md",
|
"fileName": "removeVowels.md",
|
||||||
"text": "Returns all the vowels in a `str` replaced by `repl`.\n\nUse `String.replace()` with a regexp to replace all vowels in `str`.\nOmot `repl` to use a default value of `''`.",
|
"text": "Returns all the vowels in a `str` replaced by `repl`.\n\nUse `String.prototype.replace()` with a regexp to replace all vowels in `str`.\nOmot `repl` to use a default value of `''`.",
|
||||||
"codeBlocks": [
|
"codeBlocks": [
|
||||||
"const removeVowels = (str, repl = '') => str.replace(/[aeiou]/gi, repl);",
|
"const removeVowels = (str, repl = '') => str.replace(/[aeiou]/gi, repl);",
|
||||||
"removeVowels(\"foobAr\"); // \"fbr\"\nremoveVowels(\"foobAr\",\"*\"); // \"f**b*r\""
|
"removeVowels(\"foobAr\"); // \"fbr\"\nremoveVowels(\"foobAr\",\"*\"); // \"f**b*r\""
|
||||||
@ -347,7 +347,7 @@
|
|||||||
"type": "snippet",
|
"type": "snippet",
|
||||||
"attributes": {
|
"attributes": {
|
||||||
"fileName": "solveRPN.md",
|
"fileName": "solveRPN.md",
|
||||||
"text": "Solves the given mathematical expression in [reverse polish notation](https://en.wikipedia.org/wiki/Reverse_Polish_notation).\nThrows appropriate errors if there are unrecognized symbols or the expression is wrong. The valid operators are :- `+`,`-`,`*`,`/`,`^`,`**` (`^`&`**` are the exponential symbols and are same). This snippet does not supports any unary operators.\n\nUse a dictionary, `OPERATORS` to specify each operator's matching mathematical operation.\nUse `String.replace()` with a regular expression to replace `^` with `**`, `String.split()` to tokenize the string and `Array.filter()` to remove empty tokens.\nUse `Array.forEach()` to parse each `symbol`, evaluate it as a numeric value or operator and solve the mathematical expression.\nNumeric values are converted to floating point numbers and pushed to a `stack`, while operators are evaluated using the `OPERATORS` dictionary and pop elements from the `stack` to apply operations.",
|
"text": "Solves the given mathematical expression in [reverse polish notation](https://en.wikipedia.org/wiki/Reverse_Polish_notation).\nThrows appropriate errors if there are unrecognized symbols or the expression is wrong. The valid operators are :- `+`,`-`,`*`,`/`,`^`,`**` (`^`&`**` are the exponential symbols and are same). This snippet does not supports any unary operators.\n\nUse a dictionary, `OPERATORS` to specify each operator's matching mathematical operation.\nUse `String.prototype.replace()` with a regular expression to replace `^` with `**`, `String.prototype.split()` to tokenize the string and `Array.prototype.filter()` to remove empty tokens.\nUse `Array.prototype.forEach()` to parse each `symbol`, evaluate it as a numeric value or operator and solve the mathematical expression.\nNumeric values are converted to floating point numbers and pushed to a `stack`, while operators are evaluated using the `OPERATORS` dictionary and pop elements from the `stack` to apply operations.",
|
||||||
"codeBlocks": [
|
"codeBlocks": [
|
||||||
"const solveRPN = rpn => {\n const OPERATORS = {\n '*': (a, b) => a * b,\n '+': (a, b) => a + b,\n '-': (a, b) => a - b,\n '/': (a, b) => a / b,\n '**': (a, b) => a ** b\n };\n const [stack, solve] = [\n [],\n rpn\n .replace(/\\^/g, '**')\n .split(/\\s+/g)\n .filter(el => !/\\s+/.test(el) && el !== '')\n ];\n solve.forEach(symbol => {\n if (!isNaN(parseFloat(symbol)) && isFinite(symbol)) {\n stack.push(symbol);\n } else if (Object.keys(OPERATORS).includes(symbol)) {\n const [a, b] = [stack.pop(), stack.pop()];\n stack.push(OPERATORS[symbol](parseFloat(b), parseFloat(a)));\n } else {\n throw `${symbol} is not a recognized symbol`;\n }\n });\n if (stack.length === 1) return stack.pop();\n else throw `${rpn} is not a proper RPN. Please check it and try again`;\n};",
|
"const solveRPN = rpn => {\n const OPERATORS = {\n '*': (a, b) => a * b,\n '+': (a, b) => a + b,\n '-': (a, b) => a - b,\n '/': (a, b) => a / b,\n '**': (a, b) => a ** b\n };\n const [stack, solve] = [\n [],\n rpn\n .replace(/\\^/g, '**')\n .split(/\\s+/g)\n .filter(el => !/\\s+/.test(el) && el !== '')\n ];\n solve.forEach(symbol => {\n if (!isNaN(parseFloat(symbol)) && isFinite(symbol)) {\n stack.push(symbol);\n } else if (Object.keys(OPERATORS).includes(symbol)) {\n const [a, b] = [stack.pop(), stack.pop()];\n stack.push(OPERATORS[symbol](parseFloat(b), parseFloat(a)));\n } else {\n throw `${symbol} is not a recognized symbol`;\n }\n });\n if (stack.length === 1) return stack.pop();\n else throw `${rpn} is not a proper RPN. Please check it and try again`;\n};",
|
||||||
"solveRPN('15 7 1 1 + - / 3 * 2 1 1 + + -'); // 5\nsolveRPN('2 3 ^'); // 8"
|
"solveRPN('15 7 1 1 + - / 3 * 2 1 1 + + -'); // 5\nsolveRPN('2 3 ^'); // 8"
|
||||||
|
|||||||
@ -2,8 +2,8 @@
|
|||||||
|
|
||||||
Converts a comma-separated values (CSV) string to a 2D array.
|
Converts a comma-separated values (CSV) string to a 2D array.
|
||||||
|
|
||||||
Use `Array.slice()` and `Array.indexOf('\n')` to remove the first row (title row) if `omitFirstRow` is `true`.
|
Use `Array.prototype.slice()` and `Array.prototype.indexOf('\n')` to remove the first row (title row) if `omitFirstRow` is `true`.
|
||||||
Use `String.split('\n')` to create a string for each row, then `String.split(delimiter)` to separate the values in each row.
|
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 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.
|
Omit the third argument, `omitFirstRow`, to include the first row (title row) of the CSV string.
|
||||||
|
|
||||||
|
|||||||
@ -3,9 +3,9 @@
|
|||||||
Converts a comma-separated values (CSV) string to a 2D array of objects.
|
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.
|
The first row of the string is used as the title row.
|
||||||
|
|
||||||
Use `Array.slice()` and `Array.indexOf('\n')` and `String.split(delimiter)` to separate the first row (title row) into values.
|
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.split('\n')` to create a string for each row, then `Array.map()` and `String.split(delimiter)` to separate the values in each row.
|
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.reduce()` to create an object for each row's values, with the keys parsed from the title 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 `,`.
|
Omit the second argument, `delimiter`, to use a default delimiter of `,`.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
|
|||||||
@ -2,9 +2,9 @@
|
|||||||
|
|
||||||
Converts an array of objects to a comma-separated values (CSV) string that contains only the `columns` specified.
|
Converts an array of objects to a comma-separated values (CSV) string that contains only the `columns` specified.
|
||||||
|
|
||||||
Use `Array.join(demiliter)` to combine all the names in `columns` to create the first row.
|
Use `Array.prototype.join(demiliter)` to combine all the names in `columns` to create the first row.
|
||||||
Use `Array.map()` and `Array.reduce()` to create a row for each object, substituting non-existent values with empty strings and only mapping values in `columns`.
|
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.join('\n')` to combine all rows into a string.
|
Use `Array.prototype.join('\n')` to combine all rows into a string.
|
||||||
Omit the third argument, `delimiter`, to use a default delimiter of `,`.
|
Omit the third argument, `delimiter`, to use a default delimiter of `,`.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
|
|||||||
@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
Joins all given URL segments together, then normalizes the resulting URL.
|
Joins all given URL segments together, then normalizes the resulting URL.
|
||||||
|
|
||||||
Use `String.join('/')` to combine URL segments, then a series of `String.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
|
```js
|
||||||
const URLJoin = (...args) =>
|
const URLJoin = (...args) =>
|
||||||
|
|||||||
@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
Returns `true` if the provided predicate function returns `true` for all elements in a collection, `false` otherwise.
|
Returns `true` if the provided predicate function returns `true` for all elements in a collection, `false` otherwise.
|
||||||
|
|
||||||
Use `Array.every()` to test if all elements in the collection return `true` based on `fn`.
|
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.
|
Omit the second argument, `fn`, to use `Boolean` as a default.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
|
|||||||
@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
Check if all elements in an array are equal.
|
Check if all elements in an array are equal.
|
||||||
|
|
||||||
Use `Array.every()` to check if all the elements of the array are the same as the first one.
|
Use `Array.prototype.every()` to check if all the elements of the array are the same as the first one.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const allEqual = arr => arr.every(val => val === arr[0]);
|
const allEqual = arr => arr.every(val => val === arr[0]);
|
||||||
|
|||||||
@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
Returns `true` if the provided predicate function returns `true` for at least one element in a collection, `false` otherwise.
|
Returns `true` if the provided predicate function returns `true` for at least one element in a collection, `false` otherwise.
|
||||||
|
|
||||||
Use `Array.some()` to test if any elements in the collection return `true` based on `fn`.
|
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.
|
Omit the second argument, `fn`, to use `Boolean` as a default.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
|
|||||||
@ -2,8 +2,8 @@
|
|||||||
|
|
||||||
Converts a 2D array to a comma-separated values (CSV) string.
|
Converts a 2D array to a comma-separated values (CSV) string.
|
||||||
|
|
||||||
Use `Array.map()` and `Array.join(delimiter)` to combine individual 1D arrays (rows) into strings.
|
Use `Array.prototype.map()` and `Array.prototype.join(delimiter)` to combine individual 1D arrays (rows) into strings.
|
||||||
Use `Array.join('\n')` to combine all rows into a CSV string, separating each row with a newline.
|
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 `,`.
|
Omit the second argument, `delimiter`, to use a default delimiter of `,`.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
|
|||||||
@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
Converts the given array elements into `<li>` tags and appends them to the list of the given id.
|
Converts the given array elements into `<li>` tags and appends them to the list of the given id.
|
||||||
|
|
||||||
Use `Array.map()`, `document.querySelector()`, and an anonymous inner closure to create a list of html tags.
|
Use `Array.prototype.map()`, `document.querySelector()`, and an anonymous inner closure to create a list of html tags.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const arrayToHtmlList = (arr, listID) =>
|
const arrayToHtmlList = (arr, listID) =>
|
||||||
|
|||||||
@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
Creates a function that accepts up to `n` arguments, ignoring any additional arguments.
|
Creates a function that accepts up to `n` arguments, ignoring any additional arguments.
|
||||||
|
|
||||||
Call the provided function, `fn`, with up to `n` arguments, using `Array.slice(0,n)` and the spread operator (`...`).
|
Call the provided function, `fn`, with up to `n` arguments, using `Array.prototype.slice(0,n)` and the spread operator (`...`).
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const ary = (fn, n) => (...args) => fn(...args.slice(0, n));
|
const ary = (fn, n) => (...args) => fn(...args.slice(0, n));
|
||||||
|
|||||||
@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
Returns the average of two or more numbers.
|
Returns the average of two or more numbers.
|
||||||
|
|
||||||
Use `Array.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
|
```js
|
||||||
const average = (...nums) => nums.reduce((acc, val) => acc + val, 0) / nums.length;
|
const average = (...nums) => nums.reduce((acc, val) => acc + val, 0) / nums.length;
|
||||||
|
|||||||
@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
Returns the average of an array, after mapping each element to a value using the provided function.
|
Returns the average of an array, after mapping each element to a value using the provided function.
|
||||||
|
|
||||||
Use `Array.map()` to map each element to the value returned by `fn`, `Array.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
|
```js
|
||||||
const averageBy = (arr, fn) =>
|
const averageBy = (arr, fn) =>
|
||||||
|
|||||||
@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
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.
|
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.reduce()` and `Array.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
|
```js
|
||||||
const bifurcate = (arr, filter) =>
|
const bifurcate = (arr, filter) =>
|
||||||
|
|||||||
@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
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.
|
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.reduce()` and `Array.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
|
```js
|
||||||
const bifurcateBy = (arr, fn) =>
|
const bifurcateBy = (arr, fn) =>
|
||||||
|
|||||||
@ -2,8 +2,8 @@
|
|||||||
|
|
||||||
Creates a function that invokes `fn` with a given context, optionally adding any additional supplied parameters to the beginning of the arguments.
|
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.apply()` to apply the given `context` to `fn`.
|
Return a `function` that uses `Function.prototype.apply()` to apply the given `context` to `fn`.
|
||||||
Use `Array.concat()` to prepend any additional supplied parameters to the arguments.
|
Use `Array.prototype.concat()` to prepend any additional supplied parameters to the arguments.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const bind = (fn, context, ...boundArgs) => (...args) => fn.apply(context, [...boundArgs, ...args]);
|
const bind = (fn, context, ...boundArgs) => (...args) => fn.apply(context, [...boundArgs, ...args]);
|
||||||
|
|||||||
@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
Binds methods of an object to the object itself, overwriting the existing method.
|
Binds methods of an object to the object itself, overwriting the existing method.
|
||||||
|
|
||||||
Use `Array.forEach()` to return a `function` that uses `Function.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
|
```js
|
||||||
const bindAll = (obj, ...fns) =>
|
const bindAll = (obj, ...fns) =>
|
||||||
|
|||||||
@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
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.
|
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.apply()` to bind `context[fn]` to `context`.
|
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.
|
Use the spread operator (`...`) to prepend any additional supplied parameters to the arguments.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
|
|||||||
@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
Capitalizes the first letter of a string.
|
Capitalizes the first letter of a string.
|
||||||
|
|
||||||
Use array destructuring and `String.toUpperCase()` to capitalize first letter, `...rest` to get array of characters after first letter and then `Array.join('')` to make it a string again.
|
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.
|
Omit the `lowerRest` parameter to keep the rest of the string intact, or set it to `true` to convert to lowercase.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
|
|||||||
@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
Capitalizes the first letter of every word in a string.
|
Capitalizes the first letter of every word in a string.
|
||||||
|
|
||||||
Use `String.replace()` to match the first character of each word and `String.toUpperCase()` to capitalize it.
|
Use `String.prototype.replace()` to match the first character of each word and `String.prototype.toUpperCase()` to capitalize it.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const capitalizeEveryWord = str => str.replace(/\b[a-z]/g, char => char.toUpperCase());
|
const capitalizeEveryWord = str => str.replace(/\b[a-z]/g, char => char.toUpperCase());
|
||||||
|
|||||||
@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
Casts the provided value as an array if it's not one.
|
Casts the provided value as an array if it's not one.
|
||||||
|
|
||||||
Use `Array.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
|
```js
|
||||||
const castArray = val => (Array.isArray(val) ? val : [val]);
|
const castArray = val => (Array.isArray(val) ? val : [val]);
|
||||||
|
|||||||
@ -3,7 +3,7 @@
|
|||||||
Chunks an array into smaller arrays of a specified size.
|
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.from()` to create a new array, that fits the number of chunks that will be produced.
|
||||||
Use `Array.slice()` to map each element of the new array to a chunk the length of `size`.
|
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.
|
If the original array can't be split evenly, the final chunk will contain the remaining elements.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
|
|||||||
@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
Returns the first non-null/undefined argument.
|
Returns the first non-null/undefined argument.
|
||||||
|
|
||||||
Use `Array.find()` to return the first non `null`/`undefined` argument.
|
Use `Array.prototype.find()` to return the first non `null`/`undefined` argument.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const coalesce = (...args) => args.find(_ => ![undefined, null].includes(_));
|
const coalesce = (...args) => args.find(_ => ![undefined, null].includes(_));
|
||||||
|
|||||||
@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
Returns a customized coalesce function that returns the first argument that returns `true` from the provided argument validation function.
|
Returns a customized coalesce function that returns the first argument that returns `true` from the provided argument validation function.
|
||||||
|
|
||||||
Use `Array.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
|
```js
|
||||||
const coalesceFactory = valid => (...args) => args.find(valid);
|
const coalesceFactory = valid => (...args) => args.find(valid);
|
||||||
|
|||||||
@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
Removes falsey values from an array.
|
Removes falsey values from an array.
|
||||||
|
|
||||||
Use `Array.filter()` to filter out falsey values (`false`, `null`, `0`, `""`, `undefined`, and `NaN`).
|
Use `Array.prototype.filter()` to filter out falsey values (`false`, `null`, `0`, `""`, `undefined`, and `NaN`).
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const compact = arr => arr.filter(Boolean);
|
const compact = arr => arr.filter(Boolean);
|
||||||
|
|||||||
@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
Performs right-to-left function composition.
|
Performs right-to-left function composition.
|
||||||
|
|
||||||
Use `Array.reduce()` to perform 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.
|
The last (rightmost) function can accept one or more arguments; the remaining functions must be unary.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
|
|||||||
@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
Performs left-to-right function composition.
|
Performs left-to-right function composition.
|
||||||
|
|
||||||
Use `Array.reduce()` to perform 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.
|
The first (leftmost) function can accept one or more arguments; the remaining functions must be unary.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
|
|||||||
@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
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.
|
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.map()` and `Function.apply()` to apply each function to the given arguments.
|
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 the spread operator (`...`) to call `coverger` with the results of all other functions.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
|
|||||||
@ -2,8 +2,8 @@
|
|||||||
|
|
||||||
Groups the elements of an array based on the given function and returns the count of elements in each group.
|
Groups the elements of an array based on the given function and returns the count of elements in each group.
|
||||||
|
|
||||||
Use `Array.map()` to map the values of an array to a function or property name.
|
Use `Array.prototype.map()` to map the values of an array to a function or property name.
|
||||||
Use `Array.reduce()` to create an object, where the keys are produced from the mapped results.
|
Use `Array.prototype.reduce()` to create an object, where the keys are produced from the mapped results.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const countBy = (arr, fn) =>
|
const countBy = (arr, fn) =>
|
||||||
|
|||||||
@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
Counts the occurrences of a value in an array.
|
Counts the occurrences of a value in an array.
|
||||||
|
|
||||||
Use `Array.reduce()` to increment a counter each time you encounter the specific value inside the array.
|
Use `Array.prototype.reduce()` to increment a counter each time you encounter the specific value inside the array.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const countOccurrences = (arr, val) => arr.reduce((a, v) => (v === val ? a + 1 : a), 0);
|
const countOccurrences = (arr, val) => arr.reduce((a, v) => (v === val ? a + 1 : a), 0);
|
||||||
|
|||||||
@ -1,13 +1,13 @@
|
|||||||
### createEventHub
|
### createEventHub
|
||||||
|
|
||||||
Creates a pub/sub ([publish–subscribe](https://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern)) event hub with `emit`, `on`, and `off` methods.
|
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`.
|
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.forEach()` by passing in the data as an argument.
|
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.push()` to add the handler
|
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.
|
to the array.
|
||||||
For `off`, use `Array.findIndex()` to find the index of the handler in the event array and remove it using `Array.splice()`.
|
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
|
```js
|
||||||
const createEventHub = () => ({
|
const createEventHub = () => ({
|
||||||
hub: Object.create(null),
|
hub: Object.create(null),
|
||||||
@ -23,8 +23,8 @@ const createEventHub = () => ({
|
|||||||
if (i > -1) this.hub[event].splice(i, 1);
|
if (i > -1) this.hub[event].splice(i, 1);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
```
|
```
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const handler = data => console.log(data);
|
const handler = data => console.log(data);
|
||||||
const hub = createEventHub();
|
const hub = createEventHub();
|
||||||
@ -42,4 +42,4 @@ hub.emit('increment'); // `increment` variable is now 1
|
|||||||
|
|
||||||
// Unsubscribe: stop a specific handler from listening to the 'message' event
|
// Unsubscribe: stop a specific handler from listening to the 'message' event
|
||||||
hub.off('message', handler);
|
hub.off('message', handler);
|
||||||
```
|
```
|
||||||
|
|||||||
@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
Creates a debounced function that delays invoking the provided function until at least `ms` milliseconds have elapsed since the last time it was invoked.
|
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.apply()` to apply the `this` context to the function and provide the necessary arguments.
|
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.
|
Omit the second argument, `ms`, to set the timeout at a default of 0 ms.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
|
|||||||
@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
Decapitalizes the first letter of a string.
|
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.join('')` to make it a string again.
|
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.
|
Omit the `upperRest` parameter to keep the rest of the string intact, or set it to `true` to convert to uppercase.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
|
|||||||
@ -4,7 +4,7 @@ Creates a deep clone of an object.
|
|||||||
|
|
||||||
Use recursion.
|
Use recursion.
|
||||||
Use `Object.assign()` and an empty object (`{}`) to create a shallow clone of the original.
|
Use `Object.assign()` and an empty object (`{}`) to create a shallow clone of the original.
|
||||||
Use `Object.keys()` and `Array.forEach()` to determine which key-value pairs need to be deep cloned.
|
Use `Object.keys()` and `Array.prototype.forEach()` to determine which key-value pairs need to be deep cloned.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const deepClone = obj => {
|
const deepClone = obj => {
|
||||||
|
|||||||
@ -3,7 +3,7 @@
|
|||||||
Deep flattens an array.
|
Deep flattens an array.
|
||||||
|
|
||||||
Use recursion.
|
Use recursion.
|
||||||
Use `Array.concat()` with an empty array (`[]`) and the spread operator (`...`) to flatten an array.
|
Use `Array.prototype.concat()` with an empty array (`[]`) and the spread operator (`...`) to flatten an array.
|
||||||
Recursively flatten each element that is an array.
|
Recursively flatten each element that is an array.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
|
|||||||
@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
Assigns default values for all properties in an object that are `undefined`.
|
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.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
|
```js
|
||||||
const defaults = (obj, ...defs) => Object.assign({}, obj, ...defs.reverse(), obj);
|
const defaults = (obj, ...defs) => Object.assign({}, obj, ...defs.reverse(), obj);
|
||||||
|
|||||||
@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
Returns the difference between two arrays.
|
Returns the difference between two arrays.
|
||||||
|
|
||||||
Create a `Set` from `b`, then use `Array.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
|
```js
|
||||||
const difference = (a, b) => {
|
const difference = (a, b) => {
|
||||||
|
|||||||
@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
Returns the difference between two arrays, after applying the provided function to each array element of both.
|
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.filter()` in combination with `fn` on `a` to only keep values not contained in the previously created set.
|
Create a `Set` by applying `fn` to each element in `b`, then use `Array.prototype.filter()` in combination with `fn` on `a` to only keep values not contained in the previously created set.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const differenceBy = (a, b, fn) => {
|
const differenceBy = (a, b, fn) => {
|
||||||
|
|||||||
@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
Filters out all values from an array for which the comparator function does not return `true`.
|
Filters out all values from an array for which the comparator function does not return `true`.
|
||||||
|
|
||||||
Use `Array.filter()` and `Array.findIndex()` to find the appropriate values.
|
Use `Array.prototype.filter()` and `Array.prototype.findIndex()` to find the appropriate values.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const differenceWith = (arr, val, comp) => arr.filter(a => val.findIndex(b => comp(a, b)) === -1);
|
const differenceWith = (arr, val, comp) => arr.filter(a => val.findIndex(b => comp(a, b)) === -1);
|
||||||
|
|||||||
@ -3,7 +3,7 @@
|
|||||||
Returns the target value in a nested JSON object, based on the given key.
|
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`.
|
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.reduce()` to recursively call `dig` on each nested object until the first matching key/value pair is found.
|
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
|
```js
|
||||||
const dig = (obj, target) =>
|
const dig = (obj, target) =>
|
||||||
|
|||||||
@ -3,7 +3,7 @@
|
|||||||
Converts a number to an array of digits.
|
Converts a number to an array of digits.
|
||||||
|
|
||||||
Convert the number to a string, using the spread operator (`...`) to build an array.
|
Convert the number to a string, using the spread operator (`...`) to build an array.
|
||||||
Use `Array.map()` and `parseInt()` to transform each value to an integer.
|
Use `Array.prototype.map()` and `parseInt()` to transform each value to an integer.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const digitize = n => [...`${n}`].map(i => parseInt(i));
|
const digitize = n => [...`${n}`].map(i => parseInt(i));
|
||||||
|
|||||||
@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
Returns a new array with `n` elements removed from the left.
|
Returns a new array with `n` elements removed from the left.
|
||||||
|
|
||||||
Use `Array.slice()` to slice the remove the specified number of elements from the left.
|
Use `Array.prototype.slice()` to slice the remove the specified number of elements from the left.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const drop = (arr, n = 1) => arr.slice(n);
|
const drop = (arr, n = 1) => arr.slice(n);
|
||||||
|
|||||||
@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
Returns a new array with `n` elements removed from the right.
|
Returns a new array with `n` elements removed from the right.
|
||||||
|
|
||||||
Use `Array.slice()` to slice the remove the specified number of elements from the right.
|
Use `Array.prototype.slice()` to slice the remove the specified number of elements from the right.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const dropRight = (arr, n = 1) => arr.slice(0, -n);
|
const dropRight = (arr, n = 1) => arr.slice(0, -n);
|
||||||
|
|||||||
@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
Removes elements from the end of an array until the passed function returns `true`. Returns the remaining elements in the array.
|
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.slice()` to drop the last element of the array until the returned value from the function is `true`.
|
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.
|
Returns the remaining elements.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
|
|||||||
@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
Removes elements in an array until the passed function returns `true`. Returns the remaining elements in the array.
|
Removes elements in an array until the passed function returns `true`. Returns the remaining elements in the array.
|
||||||
|
|
||||||
Loop through the array, using `Array.slice()` to drop the first element of the array until the returned value from the function is `true`.
|
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.
|
Returns the remaining elements.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
|
|||||||
@ -4,7 +4,7 @@ Performs a deep comparison between two values to determine if they are equivalen
|
|||||||
|
|
||||||
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 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.
|
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.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.
|
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
|
```js
|
||||||
const equals = (a, b) => {
|
const equals = (a, b) => {
|
||||||
|
|||||||
@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
Escapes a string for use in HTML.
|
Escapes a string for use in HTML.
|
||||||
|
|
||||||
Use `String.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
|
```js
|
||||||
const escapeHTML = str =>
|
const escapeHTML = str =>
|
||||||
|
|||||||
@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
Escapes a string to use in a regular expression.
|
Escapes a string to use in a regular expression.
|
||||||
|
|
||||||
Use `String.replace()` to escape special characters.
|
Use `String.prototype.replace()` to escape special characters.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const escapeRegExp = str => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
const escapeRegExp = str => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||||
|
|||||||
@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
Returns every nth element in an array.
|
Returns every nth element in an array.
|
||||||
|
|
||||||
Use `Array.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
|
```js
|
||||||
const everyNth = (arr, nth) => arr.filter((e, i) => i % nth === nth - 1);
|
const everyNth = (arr, nth) => arr.filter((e, i) => i % nth === nth - 1);
|
||||||
|
|||||||
@ -2,8 +2,8 @@
|
|||||||
|
|
||||||
Extends a 3-digit color code to a 6-digit color code.
|
Extends a 3-digit color code to a 6-digit color code.
|
||||||
|
|
||||||
Use `Array.map()`, `String.split()` and `Array.join()` to join the mapped array for converting a 3-digit RGB notated hexadecimal color-code to the 6-digit form.
|
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.slice()` is used to remove `#` from string start since it's added once.
|
`Array.prototype.slice()` is used to remove `#` from string start since it's added once.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const extendHex = shortHex =>
|
const extendHex = shortHex =>
|
||||||
|
|||||||
@ -3,7 +3,7 @@
|
|||||||
Generates an array, containing the Fibonacci sequence, up until the nth term.
|
Generates an array, containing the Fibonacci sequence, up until the nth term.
|
||||||
|
|
||||||
Create an empty array of the specific length, initializing the first two values (`0` and `1`).
|
Create an empty array of the specific length, initializing the first two values (`0` and `1`).
|
||||||
Use `Array.reduce()` to add values into the array, using the sum of the last two values, except for the first two.
|
Use `Array.prototype.reduce()` to add values into the array, using the sum of the last two values, except for the first two.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const fibonacci = n =>
|
const fibonacci = n =>
|
||||||
|
|||||||
@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
Filters out the non-unique values in an array.
|
Filters out the non-unique values in an array.
|
||||||
|
|
||||||
Use `Array.filter()` for an array containing only the unique values.
|
Use `Array.prototype.filter()` for an array containing only the unique values.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const filterNonUnique = arr => arr.filter(i => arr.indexOf(i) === arr.lastIndexOf(i));
|
const filterNonUnique = arr => arr.filter(i => arr.indexOf(i) === arr.lastIndexOf(i));
|
||||||
|
|||||||
@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
Filters out the non-unique values in an array, based on a provided comparator function.
|
Filters out the non-unique values in an array, based on a provided comparator function.
|
||||||
|
|
||||||
Use `Array.filter()` and `Array.every()` for an array containing only the unique values, based on the comparator function, `fn`.
|
Use `Array.prototype.filter()` and `Array.prototype.every()` for an array containing only the unique values, based on the comparator function, `fn`.
|
||||||
The comparator function takes four arguments: the values of the two elements being compared and their indexes.
|
The comparator function takes four arguments: the values of the two elements being compared and their indexes.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
|
|||||||
@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
Returns the first key that satisfies the provided testing function. Otherwise `undefined` is returned.
|
Returns the first key that satisfies the provided testing function. Otherwise `undefined` is returned.
|
||||||
|
|
||||||
Use `Object.keys(obj)` to get all the properties of the object, `Array.find()` to test the provided function for each key-value pair. The callback receives three arguments - the value, the key and the object.
|
Use `Object.keys(obj)` to get all the properties of the object, `Array.prototype.find()` to test the provided function for each key-value pair. The callback receives three arguments - the value, the key and the object.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const findKey = (obj, fn) => Object.keys(obj).find(key => fn(obj[key], key, obj));
|
const findKey = (obj, fn) => Object.keys(obj).find(key => fn(obj[key], key, obj));
|
||||||
|
|||||||
@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
Returns the last element for which the provided function returns a truthy value.
|
Returns the last element for which the provided function returns a truthy value.
|
||||||
|
|
||||||
Use `Array.filter()` to remove elements for which `fn` returns falsey values, `Array.pop()` to get the last one.
|
Use `Array.prototype.filter()` to remove elements for which `fn` returns falsey values, `Array.prototype.pop()` to get the last one.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const findLast = (arr, fn) => arr.filter(fn).pop();
|
const findLast = (arr, fn) => arr.filter(fn).pop();
|
||||||
|
|||||||
@ -2,8 +2,8 @@
|
|||||||
|
|
||||||
Returns the index of the last element for which the provided function returns a truthy value.
|
Returns the index of the last element for which the provided function returns a truthy value.
|
||||||
|
|
||||||
Use `Array.map()` to map each element to an array with its index and value.
|
Use `Array.prototype.map()` to map each element to an array with its index and value.
|
||||||
Use `Array.filter()` to remove elements for which `fn` returns falsey values, `Array.pop()` to get the last one.
|
Use `Array.prototype.filter()` to remove elements for which `fn` returns falsey values, `Array.prototype.pop()` to get the last one.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const findLastIndex = (arr, fn) =>
|
const findLastIndex = (arr, fn) =>
|
||||||
|
|||||||
@ -1,9 +1,9 @@
|
|||||||
### findLastKey
|
### findLastKey
|
||||||
|
|
||||||
Returns the last key that satisfies the provided testing function.
|
Returns the last key that satisfies the provided testing function.
|
||||||
Otherwise `undefined` is returned.
|
Otherwise `undefined` is returned.
|
||||||
|
|
||||||
Use `Object.keys(obj)` to get all the properties of the object, `Array.reverse()` to reverse their order and `Array.find()` to test the provided function for each key-value pair.
|
Use `Object.keys(obj)` to get all the properties of the object, `Array.prototype.reverse()` to reverse their order and `Array.prototype.find()` to test the provided function for each key-value pair.
|
||||||
The callback receives three arguments - the value, the key and the object.
|
The callback receives three arguments - the value, the key and the object.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
|
|||||||
@ -3,7 +3,7 @@
|
|||||||
Flattens an array up to the specified depth.
|
Flattens an array up to the specified depth.
|
||||||
|
|
||||||
Use recursion, decrementing `depth` by 1 for each level of depth.
|
Use recursion, decrementing `depth` by 1 for each level of depth.
|
||||||
Use `Array.reduce()` and `Array.concat()` to merge elements or arrays.
|
Use `Array.prototype.reduce()` and `Array.prototype.concat()` to merge elements or arrays.
|
||||||
Base case, for `depth` equal to `1` stops recursion.
|
Base case, for `depth` equal to `1` stops recursion.
|
||||||
Omit the second argument, `depth` to flatten only to a depth of `1` (single flatten).
|
Omit the second argument, `depth` to flatten only to a depth of `1` (single flatten).
|
||||||
|
|
||||||
|
|||||||
@ -3,7 +3,7 @@
|
|||||||
Flatten an object with the paths for keys.
|
Flatten an object with the paths for keys.
|
||||||
|
|
||||||
Use recursion.
|
Use recursion.
|
||||||
Use `Object.keys(obj)` combined with `Array.reduce()` to convert every leaf node to a flattened path node.
|
Use `Object.keys(obj)` combined with `Array.prototype.reduce()` to convert every leaf node to a flattened path node.
|
||||||
If the value of a key is an object, the function calls itself with the appropriate `prefix` to create the path using `Object.assign()`.
|
If the value of a key is an object, the function calls itself with the appropriate `prefix` to create the path using `Object.assign()`.
|
||||||
Otherwise, it adds the appropriate prefixed key-value pair to the accumulator object.
|
Otherwise, it adds the appropriate prefixed key-value pair to the accumulator object.
|
||||||
You should always omit the second argument, `prefix`, unless you want every key to have a prefix.
|
You should always omit the second argument, `prefix`, unless you want every key to have a prefix.
|
||||||
|
|||||||
@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
Executes a provided function once for each array element, starting from the array's last element.
|
Executes a provided function once for each array element, starting from the array's last element.
|
||||||
|
|
||||||
Use `Array.slice(0)` to clone the given array, `Array.reverse()` to reverse it and `Array.forEach()` to iterate over the reversed array.
|
Use `Array.prototype.slice(0)` to clone the given array, `Array.prototype.reverse()` to reverse it and `Array.prototype.forEach()` to iterate over the reversed array.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const forEachRight = (arr, callback) =>
|
const forEachRight = (arr, callback) =>
|
||||||
|
|||||||
@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
Iterates over all own properties of an object, running a callback for each one.
|
Iterates over all own properties of an object, running a callback for each one.
|
||||||
|
|
||||||
Use `Object.keys(obj)` to get all the properties of the object, `Array.forEach()` to run the provided function for each key-value pair. The callback receives three arguments - the value, the key and the object.
|
Use `Object.keys(obj)` to get all the properties of the object, `Array.prototype.forEach()` to run the provided function for each key-value pair. The callback receives three arguments - the value, the key and the object.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const forOwn = (obj, fn) => Object.keys(obj).forEach(key => fn(obj[key], key, obj));
|
const forOwn = (obj, fn) => Object.keys(obj).forEach(key => fn(obj[key], key, obj));
|
||||||
|
|||||||
@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
Iterates over all own properties of an object in reverse, running a callback for each one.
|
Iterates over all own properties of an object in reverse, running a callback for each one.
|
||||||
|
|
||||||
Use `Object.keys(obj)` to get all the properties of the object, `Array.reverse()` to reverse their order and `Array.forEach()` to run the provided function for each key-value pair. The callback receives three arguments - the value, the key and the object.
|
Use `Object.keys(obj)` to get all the properties of the object, `Array.prototype.reverse()` to reverse their order and `Array.prototype.forEach()` to run the provided function for each key-value pair. The callback receives three arguments - the value, the key and the object.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const forOwnRight = (obj, fn) =>
|
const forOwnRight = (obj, fn) =>
|
||||||
|
|||||||
@ -3,9 +3,9 @@
|
|||||||
Returns the human readable format of the given number of milliseconds.
|
Returns the human readable format of the given number of milliseconds.
|
||||||
|
|
||||||
Divide `ms` with the appropriate values to obtain the appropriate values for `day`, `hour`, `minute`, `second` and `millisecond`.
|
Divide `ms` with the appropriate values to obtain the appropriate values for `day`, `hour`, `minute`, `second` and `millisecond`.
|
||||||
Use `Object.entries()` with `Array.filter()` to keep only non-zero values.
|
Use `Object.entries()` with `Array.prototype.filter()` to keep only non-zero values.
|
||||||
Use `Array.map()` to create the string for each value, pluralizing appropriately.
|
Use `Array.prototype.map()` to create the string for each value, pluralizing appropriately.
|
||||||
Use `String.join(', ')` to combine the values into a string.
|
Use `String.prototype.join(', ')` to combine the values into a string.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const formatDuration = ms => {
|
const formatDuration = ms => {
|
||||||
|
|||||||
@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
Converts a string from camelcase.
|
Converts a string from camelcase.
|
||||||
|
|
||||||
Use `String.replace()` to remove underscores, hyphens, and spaces and convert words to camelcase.
|
Use `String.prototype.replace()` to remove underscores, hyphens, and spaces and convert words to camelcase.
|
||||||
Omit the second argument to use a default `separator` of `_`.
|
Omit the second argument to use a default `separator` of `_`.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
|
|||||||
@ -4,7 +4,7 @@ Returns an array of function property names from own (and optionally inherited)
|
|||||||
|
|
||||||
Use `Object.keys(obj)` to iterate over the object's own properties.
|
Use `Object.keys(obj)` to iterate over the object's own properties.
|
||||||
If `inherited` is `true`, use `Object.get.PrototypeOf(obj)` to also get the object's inherited properties.
|
If `inherited` is `true`, use `Object.get.PrototypeOf(obj)` to also get the object's inherited properties.
|
||||||
Use `Array.filter()` to keep only those properties that are functions.
|
Use `Array.prototype.filter()` to keep only those properties that are functions.
|
||||||
Omit the second argument, `inherited`, to not include inherited properties by default.
|
Omit the second argument, `inherited`, to not include inherited properties by default.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
|
|||||||
@ -3,7 +3,7 @@
|
|||||||
Initializes an array containing the numbers in the specified range where `start` and `end` are inclusive and the ratio between two terms is `step`.
|
Initializes an array containing the numbers in the specified range where `start` and `end` are inclusive and the ratio between two terms is `step`.
|
||||||
Returns an error if `step` equals `1`.
|
Returns an error if `step` equals `1`.
|
||||||
|
|
||||||
Use `Array.from()`, `Math.log()` and `Math.floor()` to create an array of the desired length, `Array.map()` to fill with the desired values in a range.
|
Use `Array.from()`, `Math.log()` and `Math.floor()` to create an array of the desired length, `Array.prototype.map()` to fill with the desired values in a range.
|
||||||
Omit the second argument, `start`, to use a default value of `1`.
|
Omit the second argument, `start`, to use a default value of `1`.
|
||||||
Omit the third argument, `step`, to use a default value of `2`.
|
Omit the third argument, `step`, to use a default value of `2`.
|
||||||
|
|
||||||
|
|||||||
@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
Retrieve a set of properties indicated by the given selectors from an object.
|
Retrieve a set of properties indicated by the given selectors from an object.
|
||||||
|
|
||||||
Use `Array.map()` for each selector, `String.replace()` to replace square brackets with dots, `String.split('.')` to split each selector, `Array.filter()` to remove empty values and `Array.reduce()` to get the value indicated by it.
|
Use `Array.prototype.map()` for each selector, `String.prototype.replace()` to replace square brackets with dots, `String.prototype.split('.')` to split each selector, `Array.prototype.filter()` to remove empty values and `Array.prototype.reduce()` to get the value indicated by it.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const get = (from, ...selectors) =>
|
const get = (from, ...selectors) =>
|
||||||
|
|||||||
@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
Returns a string of the form `HH:MM:SS` from a `Date` object.
|
Returns a string of the form `HH:MM:SS` from a `Date` object.
|
||||||
|
|
||||||
Use `Date.toString()` and `String.slice()` to get the `HH:MM:SS` part of a given `Date` object.
|
Use `Date.prototype.toString()` and `String.prototype.slice()` to get the `HH:MM:SS` part of a given `Date` object.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const getColonTimeFromDate = date => date.toTimeString().slice(0, 8);
|
const getColonTimeFromDate = date => date.toTimeString().slice(0, 8);
|
||||||
|
|||||||
@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
Returns an object containing the parameters of the current URL.
|
Returns an object containing the parameters of the current URL.
|
||||||
|
|
||||||
Use `String.match()` with an appropriate regular expression to get all key-value pairs, `Array.reduce()` to map and combine them into a single object.
|
Use `String.match()` with an appropriate regular expression to get all key-value pairs, `Array.prototype.reduce()` to map and combine them into a single object.
|
||||||
Pass `location.search` as the argument to apply to the current `url`.
|
Pass `location.search` as the argument to apply to the current `url`.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
|
|||||||
@ -2,8 +2,8 @@
|
|||||||
|
|
||||||
Groups the elements of an array based on the given function.
|
Groups the elements of an array based on the given function.
|
||||||
|
|
||||||
Use `Array.map()` to map the values of an array to a function or property name.
|
Use `Array.prototype.map()` to map the values of an array to a function or property name.
|
||||||
Use `Array.reduce()` to create an object, where the keys are produced from the mapped results.
|
Use `Array.prototype.reduce()` to create an object, where the keys are produced from the mapped results.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const groupBy = (arr, fn) =>
|
const groupBy = (arr, fn) =>
|
||||||
|
|||||||
@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
Check if the current process's arguments contain the specified flags.
|
Check if the current process's arguments contain the specified flags.
|
||||||
|
|
||||||
Use `Array.every()` and `Array.includes()` to check if `process.argv` contains all the specified flags.
|
Use `Array.prototype.every()` and `Array.prototype.includes()` to check if `process.argv` contains all the specified flags.
|
||||||
Use a regular expression to test if the specified flags are prefixed with `-` or `--` and prefix them accordingly.
|
Use a regular expression to test if the specified flags are prefixed with `-` or `--` and prefix them accordingly.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
|
|||||||
@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
Redirects the page to HTTPS if its currently in HTTP. Also, pressing the back button doesn't take it back to the HTTP page as its replaced in the history.
|
Redirects the page to HTTPS if its currently in HTTP. Also, pressing the back button doesn't take it back to the HTTP page as its replaced in the history.
|
||||||
|
|
||||||
Use `location.protocol` to get the protocol currently being used. If it's not HTTPS, use `location.replace()` to replace the existing page with the HTTPS version of the page. Use `location.href` to get the full address, split it with `String.split()` and remove the protocol part of the URL.
|
Use `location.protocol` to get the protocol currently being used. If it's not HTTPS, use `location.replace()` to replace the existing page with the HTTPS version of the page. Use `location.href` to get the full address, split it with `String.prototype.split()` and remove the protocol part of the URL.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const httpsRedirect = () => {
|
const httpsRedirect = () => {
|
||||||
|
|||||||
@ -1,9 +1,9 @@
|
|||||||
### indexOfAll
|
### indexOfAll
|
||||||
|
|
||||||
Returns all indices of `val` in an array.
|
Returns all indices of `val` in an array.
|
||||||
If `val` never occurs, returns `[]`.
|
If `val` never occurs, returns `[]`.
|
||||||
|
|
||||||
Use `Array.reduce()` to loop over elements and store indices for matching elements.
|
Use `Array.prototype.reduce()` to loop over elements and store indices for matching elements.
|
||||||
Return the array of indices.
|
Return the array of indices.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
|
|||||||
@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
Initializes a 2D array of given width and height and value.
|
Initializes a 2D array of given width and height and value.
|
||||||
|
|
||||||
Use `Array.map()` to generate h rows where each is a new array of size w initialize with value. If the value is not provided, default to `null`.
|
Use `Array.prototype.map()` to generate h rows where each is a new array of size w initialize with value. If the value is not provided, default to `null`.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const initialize2DArray = (w, h, val = null) =>
|
const initialize2DArray = (w, h, val = null) =>
|
||||||
|
|||||||
@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
Initializes an array containing the numbers in the specified range (in reverse) where `start` and `end` are inclusive with their common difference `step`.
|
Initializes an array containing the numbers in the specified range (in reverse) where `start` and `end` are inclusive with their common difference `step`.
|
||||||
|
|
||||||
Use `Array.from(Math.ceil((end+1-start)/step))` to create an array of the desired length(the amounts of elements is equal to `(end-start)/step` or `(end+1-start)/step` for inclusive end), `Array.map()` to fill with the desired values in a range.
|
Use `Array.from(Math.ceil((end+1-start)/step))` to create an array of the desired length(the amounts of elements is equal to `(end-start)/step` or `(end+1-start)/step` for inclusive end), `Array.prototype.map()` to fill with the desired values in a range.
|
||||||
You can omit `start` to use a default value of `0`.
|
You can omit `start` to use a default value of `0`.
|
||||||
You can omit `step` to use a default value of `1`.
|
You can omit `step` to use a default value of `1`.
|
||||||
|
|
||||||
|
|||||||
@ -3,7 +3,7 @@
|
|||||||
Create a n-dimensional array with given value.
|
Create a n-dimensional array with given value.
|
||||||
|
|
||||||
Use recursion.
|
Use recursion.
|
||||||
Use `Array.map()` to generate rows where each is a new array initialized using `initializeNDArray`.
|
Use `Array.prototype.map()` to generate rows where each is a new array initialized using `initializeNDArray`.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const initializeNDArray = (val, ...args) =>
|
const initializeNDArray = (val, ...args) =>
|
||||||
|
|||||||
@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
Returns a list of elements that exist in both arrays.
|
Returns a list of elements that exist in both arrays.
|
||||||
|
|
||||||
Create a `Set` from `b`, then use `Array.filter()` on `a` to only keep values contained in `b`.
|
Create a `Set` from `b`, then use `Array.prototype.filter()` on `a` to only keep values contained in `b`.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const intersection = (a, b) => {
|
const intersection = (a, b) => {
|
||||||
|
|||||||
@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
Returns a list of elements that exist in both arrays, after applying the provided function to each array element of both.
|
Returns a list of elements that exist in both arrays, after applying the provided function to each array element of both.
|
||||||
|
|
||||||
Create a `Set` by applying `fn` to all elements in `b`, then use `Array.filter()` on `a` to only keep elements, which produce values contained in `b` when `fn` is applied to them.
|
Create a `Set` by applying `fn` to all elements in `b`, then use `Array.prototype.filter()` on `a` to only keep elements, which produce values contained in `b` when `fn` is applied to them.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const intersectionBy = (a, b, fn) => {
|
const intersectionBy = (a, b, fn) => {
|
||||||
|
|||||||
@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
Returns a list of elements that exist in both arrays, using a provided comparator function.
|
Returns a list of elements that exist in both arrays, using a provided comparator function.
|
||||||
|
|
||||||
Use `Array.filter()` and `Array.findIndex()` in combination with the provided comparator to determine intersecting values.
|
Use `Array.prototype.filter()` and `Array.prototype.findIndex()` in combination with the provided comparator to determine intersecting values.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const intersectionWith = (a, b, comp) => a.filter(x => b.findIndex(y => comp(x, y)) !== -1);
|
const intersectionWith = (a, b, comp) => a.filter(x => b.findIndex(y => comp(x, y)) !== -1);
|
||||||
|
|||||||
@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
Inverts the key-value pairs of an object, without mutating it. The corresponding inverted value of each inverted key is an array of keys responsible for generating the inverted value. If a function is supplied, it is applied to each inverted key.
|
Inverts the key-value pairs of an object, without mutating it. The corresponding inverted value of each inverted key is an array of keys responsible for generating the inverted value. If a function is supplied, it is applied to each inverted key.
|
||||||
|
|
||||||
Use `Object.keys()` and `Array.reduce()` to invert the key-value pairs of an object and apply the function provided (if any).
|
Use `Object.keys()` and `Array.prototype.reduce()` to invert the key-value pairs of an object and apply the function provided (if any).
|
||||||
Omit the second argument, `fn`, to get the inverted keys without applying a function to them.
|
Omit the second argument, `fn`, to get the inverted keys without applying a function to them.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
|
|||||||
@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
Checks if the provided value is of the specified type.
|
Checks if the provided value is of the specified type.
|
||||||
|
|
||||||
Ensure the value is not `undefined` or `null` using `Array.includes()`, and compare the `constructor` property on the value with `type` to check if the provided value is of the specified `type`.
|
Ensure the value is not `undefined` or `null` using `Array.prototype.includes()`, and compare the `constructor` property on the value with `type` to check if the provided value is of the specified `type`.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const is = (type, val) => ![, null].includes(val) && val.constructor === type;
|
const is = (type, val) => ![, null].includes(val) && val.constructor === type;
|
||||||
|
|||||||
@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
Checks if a string is an anagram of another string (case-insensitive, ignores spaces, punctuation and special characters).
|
Checks if a string is an anagram of another string (case-insensitive, ignores spaces, punctuation and special characters).
|
||||||
|
|
||||||
Use `String.toLowerCase()`, `String.replace()` with an appropriate regular expression to remove unnecessary characters, `String.split('')`, `Array.sort()` and `Array.join('')` on both strings to normalize them, then check if their normalized forms are equal.
|
Use `String.toLowerCase()`, `String.prototype.replace()` with an appropriate regular expression to remove unnecessary characters, `String.prototype.split('')`, `Array.prototype.sort()` and `Array.prototype.join('')` on both strings to normalize them, then check if their normalized forms are equal.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const isAnagram = (str1, str2) => {
|
const isAnagram = (str1, str2) => {
|
||||||
|
|||||||
@ -2,8 +2,8 @@
|
|||||||
|
|
||||||
Determines if the current runtime environment is a browser so that front-end modules can run on the server (Node) without throwing errors.
|
Determines if the current runtime environment is a browser so that front-end modules can run on the server (Node) without throwing errors.
|
||||||
|
|
||||||
Use `Array.includes()` on the `typeof` values of both `window` and `document` (globals usually only available in a browser environment unless they were explicitly defined), which will return `true` if one of them is `undefined`.
|
Use `Array.prototype.includes()` on the `typeof` values of both `window` and `document` (globals usually only available in a browser environment unless they were explicitly defined), which will return `true` if one of them is `undefined`.
|
||||||
`typeof` allows globals to be checked for existence without throwing a `ReferenceError`.
|
`typeof` allows globals to be checked for existence without throwing a `ReferenceError`.
|
||||||
If both of them are not `undefined`, then the current environment is assumed to be a browser.
|
If both of them are not `undefined`, then the current environment is assumed to be a browser.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
|
|||||||
@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
Returns a boolean determining if the passed value is primitive or not.
|
Returns a boolean determining if the passed value is primitive or not.
|
||||||
|
|
||||||
Use `Array.includes()` on an array of type strings which are not primitive,
|
Use `Array.prototype.includes()` on an array of type strings which are not primitive,
|
||||||
supplying the type using `typeof`.
|
supplying the type using `typeof`.
|
||||||
Since `typeof null` evaluates to `'object'`, it needs to be directly compared.
|
Since `typeof null` evaluates to `'object'`, it needs to be directly compared.
|
||||||
|
|
||||||
|
|||||||
@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
Checks if a string is upper case.
|
Checks if a string is upper case.
|
||||||
|
|
||||||
Convert the given string to upper case, using `String.toUpperCase()` and compare it to the original.
|
Convert the given string to upper case, using `String.prototype.toUpperCase()` and compare it to the original.
|
||||||
|
|
||||||
|
|
||||||
```js
|
```js
|
||||||
|
|||||||
@ -1,9 +1,9 @@
|
|||||||
### join
|
### join
|
||||||
|
|
||||||
Joins all elements of an array into a string and returns this string.
|
Joins all elements of an array into a string and returns this string.
|
||||||
Uses a separator and an end separator.
|
Uses a separator and an end separator.
|
||||||
|
|
||||||
Use `Array.reduce()` to combine elements into a string.
|
Use `Array.prototype.reduce()` to combine elements into a string.
|
||||||
Omit the second argument, `separator`, to use a default separator of `','`.
|
Omit the second argument, `separator`, to use a default separator of `','`.
|
||||||
Omit the third argument, `end`, to use the same value as `separator` by default.
|
Omit the third argument, `end`, to use the same value as `separator` by default.
|
||||||
|
|
||||||
|
|||||||
@ -4,7 +4,7 @@ Takes any number of iterable objects or objects with a `length` property and ret
|
|||||||
If multiple objects have the same length, the first one will be returned.
|
If multiple objects have the same length, the first one will be returned.
|
||||||
Returns `undefined` if no arguments are provided.
|
Returns `undefined` if no arguments are provided.
|
||||||
|
|
||||||
Use `Array.reduce()`, comparing the `length` of objects to find the longest one.
|
Use `Array.prototype.reduce()`, comparing the `length` of objects to find the longest one.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const longestItem = (val, ...vals) =>
|
const longestItem = (val, ...vals) =>
|
||||||
|
|||||||
@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
Creates a new object from the specified object, where all the keys are in lowercase.
|
Creates a new object from the specified object, where all the keys are in lowercase.
|
||||||
|
|
||||||
Use `Object.keys()` and `Array.reduce()` to create a new object from the specified object.
|
Use `Object.keys()` and `Array.prototype.reduce()` to create a new object from the specified object.
|
||||||
Convert each key in the original object to lowercase, using `String.toLowerCase()`.
|
Convert each key in the original object to lowercase, using `String.toLowerCase()`.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
|
|||||||
@ -2,9 +2,9 @@
|
|||||||
|
|
||||||
Implementation of the [Luhn Algorithm](https://en.wikipedia.org/wiki/Luhn_algorithm) used to validate a variety of identification numbers, such as credit card numbers, IMEI numbers, National Provider Identifier numbers etc.
|
Implementation of the [Luhn Algorithm](https://en.wikipedia.org/wiki/Luhn_algorithm) used to validate a variety of identification numbers, such as credit card numbers, IMEI numbers, National Provider Identifier numbers etc.
|
||||||
|
|
||||||
Use `String.split('')`, `Array.reverse()` and `Array.map()` in combination with `parseInt()` to obtain an array of digits.
|
Use `String.prototype.split('')`, `Array.prototype.reverse()` and `Array.prototype.map()` in combination with `parseInt()` to obtain an array of digits.
|
||||||
Use `Array.splice(0,1)` to obtain the last digit.
|
Use `Array.prototype.splice(0,1)` to obtain the last digit.
|
||||||
Use `Array.reduce()` to implement the Luhn Algorithm.
|
Use `Array.prototype.reduce()` to implement the Luhn Algorithm.
|
||||||
Return `true` if `sum` is divisible by `10`, `false` otherwise.
|
Return `true` if `sum` is divisible by `10`, `false` otherwise.
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@ -3,7 +3,7 @@
|
|||||||
Creates an object with keys generated by running the provided function for each key and the same values as the provided object.
|
Creates an object with keys generated by running the provided function for each key and the same values as the provided object.
|
||||||
|
|
||||||
Use `Object.keys(obj)` to iterate over the object's keys.
|
Use `Object.keys(obj)` to iterate over the object's keys.
|
||||||
Use `Array.reduce()` to create a new object with the same values and mapped keys using `fn`.
|
Use `Array.prototype.reduce()` to create a new object with the same values and mapped keys using `fn`.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const mapKeys = (obj, fn) =>
|
const mapKeys = (obj, fn) =>
|
||||||
|
|||||||
@ -2,8 +2,8 @@
|
|||||||
|
|
||||||
Creates a new string with the results of calling a provided function on every character in the calling string.
|
Creates a new string with the results of calling a provided function on every character in the calling string.
|
||||||
|
|
||||||
Use `String.split('')` and `Array.map()` to call the provided function, `fn`, for each character in `str`.
|
Use `String.prototype.split('')` and `Array.prototype.map()` to call the provided function, `fn`, for each character in `str`.
|
||||||
Use `Array.join('')` to recombine the array of characters into a string.
|
Use `Array.prototype.join('')` to recombine the array of characters into a string.
|
||||||
The callback function, `fn`, takes three arguments (the current character, the index of the current character and the string `mapString` was called upon).
|
The callback function, `fn`, takes three arguments (the current character, the index of the current character and the string `mapString` was called upon).
|
||||||
|
|
||||||
```js
|
```js
|
||||||
|
|||||||
@ -3,7 +3,7 @@
|
|||||||
Creates an object with the same keys as the provided object and values generated by running the provided function for each value.
|
Creates an object with the same keys as the provided object and values generated by running the provided function for each value.
|
||||||
|
|
||||||
Use `Object.keys(obj)` to iterate over the object's keys.
|
Use `Object.keys(obj)` to iterate over the object's keys.
|
||||||
Use `Array.reduce()` to create a new object with the same keys and mapped values using `fn`.
|
Use `Array.prototype.reduce()` to create a new object with the same keys and mapped values using `fn`.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const mapValues = (obj, fn) =>
|
const mapValues = (obj, fn) =>
|
||||||
|
|||||||
@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
Replaces all but the last `num` of characters with the specified mask character.
|
Replaces all but the last `num` of characters with the specified mask character.
|
||||||
|
|
||||||
Use `String.slice()` to grab the portion of the characters that will remain unmasked and use `String.padStart()` to fill the beginning of the string with the mask character up to the original length.
|
Use `String.prototype.slice()` to grab the portion of the characters that will remain unmasked and use `String.padStart()` to fill the beginning of the string with the mask character up to the original length.
|
||||||
Omit the second argument, `num`, to keep a default of `4` characters unmasked. If `num` is negative, the unmasked characters will be at the start of the string.
|
Omit the second argument, `num`, to keep a default of `4` characters unmasked. If `num` is negative, the unmasked characters will be at the start of the string.
|
||||||
Omit the third argument, `mask`, to use a default character of `'*'` for the mask.
|
Omit the third argument, `mask`, to use a default character of `'*'` for the mask.
|
||||||
|
|
||||||
|
|||||||
@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
Compares two objects to determine if the first one contains equivalent property values to the second one.
|
Compares two objects to determine if the first one contains equivalent property values to the second one.
|
||||||
|
|
||||||
Use `Object.keys(source)` to get all the keys of the second object, then `Array.every()`, `Object.hasOwnProperty()` and strict comparison to determine if all keys exist in the first object and have the same values.
|
Use `Object.keys(source)` to get all the keys of the second object, then `Array.prototype.every()`, `Object.hasOwnProperty()` and strict comparison to determine if all keys exist in the first object and have the same values.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const matches = (obj, source) =>
|
const matches = (obj, source) =>
|
||||||
|
|||||||
@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
Compares two objects to determine if the first one contains equivalent property values to the second one, based on a provided function.
|
Compares two objects to determine if the first one contains equivalent property values to the second one, based on a provided function.
|
||||||
|
|
||||||
Use `Object.keys(source)` to get all the keys of the second object, then `Array.every()`, `Object.hasOwnProperty()` and the provided function to determine if all keys exist in the first object and have equivalent values.
|
Use `Object.keys(source)` to get all the keys of the second object, then `Array.prototype.every()`, `Object.hasOwnProperty()` and the provided function to determine if all keys exist in the first object and have equivalent values.
|
||||||
If no function is provided, the values will be compared using the equality operator.
|
If no function is provided, the values will be compared using the equality operator.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
|
|||||||
@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
Returns the maximum value of an array, after mapping each element to a value using the provided function.
|
Returns the maximum value of an array, after mapping each element to a value using the provided function.
|
||||||
|
|
||||||
Use `Array.map()` to map each element to the value returned by `fn`, `Math.max()` to get the maximum value.
|
Use `Array.prototype.map()` to map each element to the value returned by `fn`, `Math.max()` to get the maximum value.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const maxBy = (arr, fn) => Math.max(...arr.map(typeof fn === 'function' ? fn : val => val[fn]));
|
const maxBy = (arr, fn) => Math.max(...arr.map(typeof fn === 'function' ? fn : val => val[fn]));
|
||||||
|
|||||||
@ -1,10 +1,10 @@
|
|||||||
### maxN
|
### maxN
|
||||||
|
|
||||||
Returns the `n` maximum elements from the provided array.
|
Returns the `n` maximum elements from the provided array.
|
||||||
If `n` is greater than or equal to the provided array's length, then return the original array (sorted in descending order).
|
If `n` is greater than or equal to the provided array's length, then return the original array (sorted in descending order).
|
||||||
|
|
||||||
Use `Array.sort()` combined with the spread operator (`...`) to create a shallow clone of the array and sort it in descending order.
|
Use `Array.prototype.sort()` combined with the spread operator (`...`) to create a shallow clone of the array and sort it in descending order.
|
||||||
Use `Array.slice()` to get the specified number of elements.
|
Use `Array.prototype.slice()` to get the specified number of elements.
|
||||||
Omit the second argument, `n`, to get a one-element array.
|
Omit the second argument, `n`, to get a one-element array.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user