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:
Mathias Bynens
2018-09-28 15:12:52 -04:00
parent 242a18e0a8
commit 8ee50178f3
194 changed files with 545 additions and 545 deletions

148
README.md
View File

@@ -20,7 +20,7 @@
#### Related projects
- [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 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)
### call
Given a key and a set of arguments, call them when given a context. Primarily useful in composition.
Use a closure to call a stored key with stored arguments.
### call
Given a key and a set of arguments, call them when given a context. Primarily useful in composition.
Use a closure to call a stored key with stored arguments.
```js
const call = (key, ...args) => context => context[key](...args);
```
@@ -542,18 +542,18 @@ const map = call.bind(null, 'map');
Promise.resolve([1, 2, 3])
.then(map(x => 2 * x))
.then(console.log); //[ 2, 4, 6 ]
```
```
</details>
<br>[⬆ Back to top](#table-of-contents)
### collectInto
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.
### collectInto
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.
```js
const collectInto = fn => (...args) => fn(args);
```
@@ -567,18 +567,18 @@ let p1 = Promise.resolve(1);
let p2 = Promise.resolve(2);
let p3 = new Promise(resolve => setTimeout(resolve, 2000, 3));
Pall(p1, p2, p3).then(console.log); // [1, 2, 3] (after about 2 seconds)
```
```
</details>
<br>[⬆ Back to top](#table-of-contents)
### flip
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.
### flip
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.
```js
const flip = fn => (first, ...rest) => fn(...rest, first);
```
@@ -594,7 +594,7 @@ let mergePerson = mergeFrom.bind(null, a);
mergePerson(b); // == b
b = {};
Object.assign(b, a); // == b
```
```
</details>
@@ -757,12 +757,12 @@ rearged('b', 'c', 'a'); // ['a', 'b', 'c']
<br>[⬆ Back to top](#table-of-contents)
### spreadOver
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.
### spreadOver
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.
```js
const spreadOver = fn => argsArr => fn(...argsArr);
```
@@ -773,7 +773,7 @@ const spreadOver = fn => argsArr => fn(...argsArr);
```js
const arrayMax = spreadOver(Math.max);
arrayMax([1, 2, 3]); // 3
```
```
</details>
@@ -1448,7 +1448,7 @@ head([1, 2, 3]); // 1
### indexOfAll
Returns all indices of `val` in an array.
Returns all indices of `val` in an array.
If `val` never occurs, returns `[]`.
Use `Array.reduce()` to loop over elements and store indices for matching elements.
@@ -1718,7 +1718,7 @@ isSorted([4, 3, 5]); // 0
### 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.
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.
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
const longestItem = (val, ...vals) =>
@@ -1861,7 +1861,7 @@ squareIt([1, 2, 3]); // { 1: 1, 2: 4, 3: 9 }
### 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).
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
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).
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.
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.
```js
@@ -2558,10 +2558,10 @@ sortedLastIndexBy([{ x: 4 }, { x: 5 }], { x: 4 }, o => o.x); // 1
### stableSort ![advanced](/advanced.svg)
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.
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.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).
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).
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
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.
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.
```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.
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
const httpsRedirect = () => {
@@ -3782,7 +3782,7 @@ obs.disconnect(); // Disconnects the observer and stops logging mutations on the
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.
```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).
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()`.
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.
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.
```js
@@ -3903,9 +3903,9 @@ prefix('appearance'); // 'appearance' on a supported browser, otherwise 'webkitA
Invokes the provided callback on each animation frame.
Use recursion.
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.
Use recursion.
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.
Omit the second argument, `autoStart`, to implicitly call `start` when the function is invoked.
```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.
Use `.scrollIntoView` method to scroll the element.
Use `.scrollIntoView` method to scroll the element.
Pass `{ behavior: 'smooth' }` to `.scrollIntoView` so it scrolls smoothly.
```js
@@ -4678,11 +4678,11 @@ functionName(Math.max); // max (logged in debug channel of console)
### 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.
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.
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.
Omit the second argument, `iterations`, to use the default of 100 iterations.
```js
@@ -5036,7 +5036,7 @@ unfold(f, 10); // [-10, -20, -30, -40, -50]
### 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`.
@@ -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).
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.
```js
@@ -6232,7 +6232,7 @@ console.log(arr); // ['line1', 'line2', 'line3']
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
const untildify = str => str.replace(/^~($|\/|\\)/, `${require('os').homedir()}$1`);
@@ -6494,10 +6494,10 @@ findKey(
### 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.
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.
```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.
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
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.
Useful for nesting comments, such as the ones on reddit.com.
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.
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).
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.
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`.
```js
@@ -7135,7 +7135,7 @@ const b = shallowClone(a); // a !== b
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` 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.
@@ -7308,7 +7308,7 @@ capitalize('fooBar', true); // 'Foobar'
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
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.
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
const escapeHTML = str =>
@@ -7450,7 +7450,7 @@ escapeHTML('<a href="#">Me & you</a>'); // '&lt;a href=&quot;#&quot;&gt;Me &amp;
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
const escapeRegExp = str => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
@@ -7471,7 +7471,7 @@ escapeRegExp('(test)'); // \\(test\\)
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 `_`.
```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).
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
const isAnagram = (str1, str2) => {
@@ -7699,7 +7699,7 @@ pad('foobar', 3); // 'foobar'
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()`.
```js
@@ -8016,7 +8016,7 @@ truncateString('boomerang', 7); // 'boom...'
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
const unescapeHTML = str =>
@@ -8048,7 +8048,7 @@ unescapeHTML('&lt;a href=&quot;#&quot;&gt;Me &amp; you&lt;/a&gt;'); // '<a href=
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
const URLJoin = (...args) =>
@@ -8322,7 +8322,7 @@ isNumber(1); // true
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.
```js
@@ -8757,7 +8757,7 @@ const httpGet = (url, callback, err = console.error) => {
httpGet(
'https://jsonplaceholder.typicode.com/posts/1',
console.log
); /*
); /*
Logs: {
"userId": 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.
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`.
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`.
If both of them are not `undefined`, then the current environment is assumed to be a browser.
```js
@@ -8860,7 +8860,7 @@ isBrowser(); // false (Node)
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 `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.
```js