Update top JS snippets
This commit is contained in:
@ -2,14 +2,14 @@
|
||||
title: CSVToArray
|
||||
tags: string,array,intermediate
|
||||
firstSeen: 2018-06-27T20:57:54+03:00
|
||||
lastUpdated: 2020-11-03T21:46:13+02:00
|
||||
lastUpdated: 2021-10-13T19:29:39+02:00
|
||||
---
|
||||
|
||||
Converts a comma-separated values (CSV) string to a 2D array.
|
||||
|
||||
- Use `Array.prototype.slice()` and `Array.prototype.indexOf('\n')` to remove the first row (title row) if `omitFirstRow` is `true`.
|
||||
- Use `String.prototype.split('\n')` to create a string for each row, then `String.prototype.split(delimiter)` to separate the values in each row.
|
||||
- Omit the second argument, `delimiter`, to use a default delimiter of `,`.
|
||||
- Omit the second argument, `delimiter`, to use a default delimiter of `','`.
|
||||
- Omit the third argument, `omitFirstRow`, to include the first row (title row) of the CSV string.
|
||||
|
||||
```js
|
||||
|
||||
@ -2,15 +2,15 @@
|
||||
title: JSONtoCSV
|
||||
tags: array,string,object,advanced
|
||||
firstSeen: 2018-07-06T20:25:46+03:00
|
||||
lastUpdated: 2020-10-22T20:23:47+03:00
|
||||
lastUpdated: 2021-10-13T19:29:39+02:00
|
||||
---
|
||||
|
||||
Converts an array of objects to a comma-separated values (CSV) string that contains only the `columns` specified.
|
||||
|
||||
- Use `Array.prototype.join(delimiter)` to combine all the names in `columns` to create the first row.
|
||||
- Use `Array.prototype.map()` and `Array.prototype.reduce()` to create a row for each object, substituting non-existent values with empty strings and only mapping values in `columns`.
|
||||
- Use `Array.prototype.map()` and `Array.prototype.reduce()` to create a row for each object. Substitute non-existent values with empty strings and only mapping values in `columns`.
|
||||
- Use `Array.prototype.join('\n')` to combine all rows into a string.
|
||||
- Omit the third argument, `delimiter`, to use a default delimiter of `,`.
|
||||
- Omit the third argument, `delimiter`, to use a default delimiter of `','`.
|
||||
|
||||
```js
|
||||
const JSONtoCSV = (arr, columns, delimiter = ',') =>
|
||||
|
||||
@ -2,12 +2,12 @@
|
||||
title: arithmeticProgression
|
||||
tags: math,algorithm,beginner
|
||||
firstSeen: 2020-10-04T11:37:07+03:00
|
||||
lastUpdated: 2020-12-28T13:49:24+02:00
|
||||
lastUpdated: 2021-10-13T19:29:39+02:00
|
||||
---
|
||||
|
||||
Creates an array of numbers in the arithmetic progression, starting with the given positive integer and up to the specified limit.
|
||||
|
||||
- Use `Array.from()` to create an array of the desired length, `lim/n`, and a map function to fill it with the desired values in the given range.
|
||||
- Use `Array.from()` to create an array of the desired length, `lim/n`. Use a map function to fill it with the desired values in the given range.
|
||||
|
||||
```js
|
||||
const arithmeticProgression = (n, lim) =>
|
||||
|
||||
@ -2,7 +2,7 @@
|
||||
title: copyToClipboard
|
||||
tags: browser,string,event,advanced
|
||||
firstSeen: 2017-12-31T11:40:33+02:00
|
||||
lastUpdated: 2020-10-22T20:23:47+03:00
|
||||
lastUpdated: 2021-10-13T19:29:39+02:00
|
||||
---
|
||||
|
||||
Copies a string to the clipboard.
|
||||
@ -13,7 +13,7 @@ Only works as a result of user action (i.e. inside a `click` event listener).
|
||||
- Use `Document.execCommand('copy')` to copy to the clipboard.
|
||||
- Remove the `<textarea>` element from the HTML document.
|
||||
- Finally, use `Selection().addRange()` to recover the original selected range (if any).
|
||||
- ⚠️ **NOTICE:** The same functionality can be easily implemented by using the new asynchronous Clipboard API, which is still experimental but should be used in the future instead of this snippet. Find out more about it [here](https://github.com/w3c/clipboard-apis/blob/master/explainer.adoc#writing-to-the-clipboard).
|
||||
- **Note:** You can use the new asynchronous Clipboard API to implement the same functionality. It's experimental but should be used in the future instead of this snippet. Find out more about it [here](https://github.com/w3c/clipboard-apis/blob/master/explainer.adoc#writing-to-the-clipboard).
|
||||
|
||||
```js
|
||||
const copyToClipboard = str => {
|
||||
|
||||
@ -2,12 +2,12 @@
|
||||
title: debounce
|
||||
tags: function,intermediate
|
||||
firstSeen: 2018-01-28T15:18:26+02:00
|
||||
lastUpdated: 2020-10-19T18:51:03+03:00
|
||||
lastUpdated: 2021-10-13T19:29:39+02:00
|
||||
---
|
||||
|
||||
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 its last invocation.
|
||||
|
||||
- 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.
|
||||
- Each time the debounced function is invoked, clear the current pending timeout with `clearTimeout()`. Use `setTimeout()` to create a new timeout that delays invoking the function until at least `ms` milliseconds have 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.
|
||||
|
||||
|
||||
@ -2,12 +2,14 @@
|
||||
title: equals
|
||||
tags: object,array,type,recursion,advanced
|
||||
firstSeen: 2018-01-15T18:34:11+02:00
|
||||
lastUpdated: 2021-09-08T09:37:36+03:00
|
||||
lastUpdated: 2021-10-13T19:29:39+02:00
|
||||
---
|
||||
|
||||
Performs a deep comparison between two values to determine if they are equivalent.
|
||||
|
||||
- Check if the two values are identical, if they are both `Date` objects with the same time, using `Date.prototype.getTime()` or if they are both non-object values with an equivalent value (strict comparison).
|
||||
- Check if the two values are identical.
|
||||
- Check if both values are `Date` objects with the same time, using `Date.prototype.getTime()`.
|
||||
- Check if both values are non-object values with an equivalent value (strict comparison).
|
||||
- Check if only one value is `null` or `undefined` or if their prototypes differ.
|
||||
- If none of the above conditions are met, use `Object.keys()` to check if both values have the same number of keys.
|
||||
- Use `Array.prototype.every()` to check if every key in `a` exists in `b` and if they are equivalent by calling `equals()` recursively.
|
||||
|
||||
@ -2,13 +2,13 @@
|
||||
title: escapeHTML
|
||||
tags: string,browser,regexp,intermediate
|
||||
firstSeen: 2017-12-29T15:09:21+02:00
|
||||
lastUpdated: 2020-10-19T18:51:03+03:00
|
||||
lastUpdated: 2021-10-13T19:29:39+02:00
|
||||
---
|
||||
|
||||
Escapes a string for use in HTML.
|
||||
|
||||
- Use `String.prototype.replace()` with a regexp that matches the characters that need to be escaped.
|
||||
- Use the callback function to replace each character instance with its associated escaped character using a dictionary (object).
|
||||
- Use the callback function to replace each character instance with its associated escaped character using a dictionary object.
|
||||
|
||||
```js
|
||||
const escapeHTML = str =>
|
||||
@ -26,6 +26,6 @@ const escapeHTML = str =>
|
||||
```
|
||||
|
||||
```js
|
||||
escapeHTML('<a href="#">Me & you</a>');
|
||||
escapeHTML('<a href="#">Me & you</a>');
|
||||
// '<a href="#">Me & you</a>'
|
||||
```
|
||||
|
||||
@ -2,14 +2,14 @@
|
||||
title: formatSeconds
|
||||
tags: date,math,string,intermediate
|
||||
firstSeen: 2021-05-09T12:44:55+03:00
|
||||
lastUpdated: 2021-05-17T08:59:17+03:00
|
||||
lastUpdated: 2021-10-13T19:29:39+02:00
|
||||
---
|
||||
|
||||
Returns the ISO format of the given number of seconds.
|
||||
|
||||
- Divide `s` with the appropriate values to obtain the appropriate values for `hour`, `minute` and `second`.
|
||||
- Store the `sign` in a variable to prepend it to the result.
|
||||
- Use `Array.prototype.map()` in combination with `Array.prototype.floor()` and `String.prototype.padStart()` to stringify and format each segment.
|
||||
- Use `Array.prototype.map()` in combination with `Math.floor()` and `String.prototype.padStart()` to stringify and format each segment.
|
||||
- Use `String.prototype.join(':')` to combine the values into a string.
|
||||
|
||||
```js
|
||||
|
||||
@ -2,16 +2,16 @@
|
||||
title: hashBrowser
|
||||
tags: browser,promise,advanced
|
||||
firstSeen: 2018-01-17T14:09:01+02:00
|
||||
lastUpdated: 2020-10-22T20:23:47+03:00
|
||||
lastUpdated: 2021-10-13T19:29:39+02:00
|
||||
---
|
||||
|
||||
Creates a hash for a value using the [SHA-256](https://en.wikipedia.org/wiki/SHA-2) algorithm.
|
||||
Returns a promise.
|
||||
|
||||
- Use the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) API to create a hash for the given value.
|
||||
- Create a new `TextEncoder` and use it to encode `val`, passing its value to `SubtleCrypto.digest()` to generate a digest of the given data.
|
||||
- Create a new `TextEncoder` and use it to encode `val`. Pass its value to `SubtleCrypto.digest()` to generate a digest of the given data.
|
||||
- Use `DataView.prototype.getUint32()` to read data from the resolved `ArrayBuffer`.
|
||||
- Add the data to an array using `Array.prototype.push()` after converting it to its hexadecimal representation using `Number.prototype.toString(16)`.
|
||||
- Convert the data to it hexadecimal representation using `Number.prototype.toString(16)`. Add the data to an array using `Array.prototype.push()`.
|
||||
- Finally, use `Array.prototype.join()` to combine values in the array of `hexes` into a string.
|
||||
|
||||
```js
|
||||
|
||||
@ -2,7 +2,7 @@
|
||||
title: hashNode
|
||||
tags: node,promise,advanced
|
||||
firstSeen: 2018-01-17T14:09:01+02:00
|
||||
lastUpdated: 2020-10-19T22:30:46+03:00
|
||||
lastUpdated: 2021-10-13T19:29:39+02:00
|
||||
---
|
||||
|
||||
Creates a hash for a value using the [SHA-256](https://en.wikipedia.org/wiki/SHA-2) algorithm.
|
||||
@ -10,7 +10,7 @@ Returns a promise.
|
||||
|
||||
- Use `crypto.createHash()` to create a `Hash` object with the appropriate algorithm.
|
||||
- Use `hash.update()` to add the data from `val` to the `Hash`, `hash.digest()` to calculate the digest of the data.
|
||||
- Use `setTimeout()` to prevent blocking on a long operation, and return a `Promise` to give it a familiar interface.
|
||||
- Use `setTimeout()` to prevent blocking on a long operation. Return a `Promise` to give it a familiar interface.
|
||||
|
||||
```js
|
||||
const crypto = require('crypto');
|
||||
|
||||
@ -2,12 +2,12 @@
|
||||
title: kNearestNeighbors
|
||||
tags: algorithm,array,advanced
|
||||
firstSeen: 2020-12-28T16:31:43+02:00
|
||||
lastUpdated: 2020-12-29T16:31:16+02:00
|
||||
lastUpdated: 2021-10-13T19:29:39+02:00
|
||||
---
|
||||
|
||||
Classifies a data point relative to a labelled data set, using the [k-nearest neighbors](https://en.wikipedia.org/wiki/K-nearest_neighbors_algorithm) algorithm.
|
||||
|
||||
- Use `Array.prototype.map()` to map the `data` to objects containing the euclidean distance of each element from `point`, calculated using `Math.hypot()`, `Object.keys()` and its `label`.
|
||||
- Use `Array.prototype.map()` to map the `data` to objects. Each object contains the euclidean distance of the element from `point`, calculated using `Math.hypot()`, `Object.keys()` and its `label`.
|
||||
- Use `Array.prototype.sort()` and `Array.prototype.slice()` to get the `k` nearest neighbors of `point`.
|
||||
- Use `Array.prototype.reduce()` in combination with `Object.keys()` and `Array.prototype.indexOf()` to find the most frequent `label` among them.
|
||||
|
||||
|
||||
@ -2,10 +2,10 @@
|
||||
title: luhnCheck
|
||||
tags: math,algorithm,advanced
|
||||
firstSeen: 2018-01-03T11:02:35+02:00
|
||||
lastUpdated: 2020-12-28T13:49:24+02:00
|
||||
lastUpdated: 2021-10-13T19:29:39+02:00
|
||||
---
|
||||
|
||||
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.
|
||||
Implements 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.prototype.split('')`, `Array.prototype.reverse()` and `Array.prototype.map()` in combination with `parseInt()` to obtain an array of digits.
|
||||
- Use `Array.prototype.splice(0, 1)` to obtain the last digit.
|
||||
|
||||
@ -2,7 +2,7 @@
|
||||
title: quickSort
|
||||
tags: algorithm,array,recursion,advanced
|
||||
firstSeen: 2017-12-28T13:42:41+02:00
|
||||
lastUpdated: 2020-12-29T13:03:18+02:00
|
||||
lastUpdated: 2021-10-13T19:29:39+02:00
|
||||
---
|
||||
|
||||
Sorts an array of numbers, using the quicksort algorithm.
|
||||
@ -11,7 +11,7 @@ Sorts an array of numbers, using the quicksort algorithm.
|
||||
- Use the spread operator (`...`) to clone the original array, `arr`.
|
||||
- If the `length` of the array is less than `2`, return the cloned array.
|
||||
- Use `Math.floor()` to calculate the index of the pivot element.
|
||||
- Use `Array.prototype.reduce()` and `Array.prototype.push()` to split the array into two subarrays (elements smaller or equal to the `pivot` and elements greater than it), destructuring the result into two arrays.
|
||||
- Use `Array.prototype.reduce()` and `Array.prototype.push()` to split the array into two subarrays. The first one contains elements smaller than or equal to `pivot` and the second on elements greather than it. Destructure the result into two arrays.
|
||||
- Recursively call `quickSort()` on the created subarrays.
|
||||
|
||||
```js
|
||||
|
||||
@ -2,14 +2,14 @@
|
||||
title: renderElement
|
||||
tags: browser,recursion,advanced
|
||||
firstSeen: 2020-05-03T11:55:42+03:00
|
||||
lastUpdated: 2020-11-03T22:11:18+02:00
|
||||
lastUpdated: 2021-10-13T19:29:39+02:00
|
||||
---
|
||||
|
||||
Renders the given DOM tree in the specified DOM element.
|
||||
|
||||
- Destructure the first argument into `type` and `props`, using `type` to determine if the given element is a text element.
|
||||
- Destructure the first argument into `type` and `props`. Use `type` to determine if the given element is a text element.
|
||||
- Based on the element's `type`, use either `Document.createTextNode()` or `Document.createElement()` to create the DOM element.
|
||||
- Use `Object.keys()` to add attributes to the DOM element and setting event listeners, as necessary.
|
||||
- Use `Object.keys()` to add attributes to the DOM element and set event listeners, as necessary.
|
||||
- Use recursion to render `props.children`, if any.
|
||||
- Finally, use `Node.appendChild()` to append the DOM element to the specified `container`.
|
||||
|
||||
|
||||
@ -2,14 +2,14 @@
|
||||
title: selectionSort
|
||||
tags: algorithm,array,intermediate
|
||||
firstSeen: 2020-12-27T22:22:44+02:00
|
||||
lastUpdated: 2020-12-29T13:04:24+02:00
|
||||
lastUpdated: 2021-10-13T19:29:39+02:00
|
||||
---
|
||||
|
||||
Sorts an array of numbers, using the selection sort algorithm.
|
||||
|
||||
- Use the spread operator (`...`) to clone the original array, `arr`.
|
||||
- Use a `for` loop to iterate over elements in the array.
|
||||
- Use `Array.prototype.slice()` and `Array.prototype.reduce()` to find the index of the minimum element in the subarray to the right of the current index and perform a swap, if necessary.
|
||||
- Use `Array.prototype.slice()` and `Array.prototype.reduce()` to find the index of the minimum element in the subarray to the right of the current index. Perform a swap, if necessary.
|
||||
|
||||
```js
|
||||
const selectionSort = arr => {
|
||||
|
||||
@ -2,7 +2,7 @@
|
||||
title: throttle
|
||||
tags: function,advanced
|
||||
firstSeen: 2018-01-28T15:23:01+02:00
|
||||
lastUpdated: 2020-09-15T16:28:04+03:00
|
||||
lastUpdated: 2021-10-13T19:29:39+02:00
|
||||
---
|
||||
|
||||
Creates a throttled function that only invokes the provided function at most once per every `wait` milliseconds
|
||||
@ -11,7 +11,7 @@ Creates a throttled function that only invokes the provided function at most onc
|
||||
- Use `Function.prototype.apply()` to apply the `this` context to the function and provide the necessary `arguments`.
|
||||
- Use `Date.now()` to keep track of the last time the throttled function was invoked.
|
||||
- Use a variable, `inThrottle`, to prevent a race condition between the first execution of `fn` and the next loop.
|
||||
- Omit the second argument, `wait`, to set the timeout at a default of 0 ms.
|
||||
- Omit the second argument, `wait`, to set the timeout at a default of `0` ms.
|
||||
|
||||
```js
|
||||
const throttle = (fn, wait) => {
|
||||
|
||||
@ -2,12 +2,12 @@
|
||||
title: toISOStringWithTimezone
|
||||
tags: date,intermediate
|
||||
firstSeen: 2020-10-07T09:25:05+03:00
|
||||
lastUpdated: 2020-10-22T20:24:30+03:00
|
||||
lastUpdated: 2021-10-13T19:29:39+02:00
|
||||
---
|
||||
|
||||
Converts a date to extended ISO format (ISO 8601), including timezone offset.
|
||||
|
||||
- Use `Date.prototype.getTimezoneOffset()` to get the timezone offset and reverse it, storing its sign in `diff`.
|
||||
- Use `Date.prototype.getTimezoneOffset()` to get the timezone offset and reverse it. Store its sign in `diff`.
|
||||
- Define a helper function, `pad`, that normalizes any passed number to an integer using `Math.floor()` and `Math.abs()` and pads it to `2` digits, using `String.prototype.padStart()`.
|
||||
- Use `pad()` and the built-in methods in the `Date` prototype to build the ISO 8601 string with timezone offset.
|
||||
|
||||
|
||||
@ -2,12 +2,12 @@
|
||||
title: uniqueElementsBy
|
||||
tags: array,intermediate
|
||||
firstSeen: 2018-07-18T20:49:07+03:00
|
||||
lastUpdated: 2020-10-22T20:24:44+03:00
|
||||
lastUpdated: 2021-10-13T19:29:39+02:00
|
||||
---
|
||||
|
||||
Finds all unique values of an array, based on a provided comparator function.
|
||||
|
||||
- Use `Array.prototype.reduce()` and `Array.prototype.some()` for an array containing only the first unique occurrence of each value, based on the comparator function, `fn`.
|
||||
- Use `Array.prototype.reduce()` and `Array.prototype.some()` to create an array containing only the first unique occurrence of each value, based on the comparator function, `fn`.
|
||||
- The comparator function takes two arguments: the values of the two elements being compared.
|
||||
|
||||
```js
|
||||
|
||||
@ -2,12 +2,12 @@
|
||||
title: uniqueElementsByRight
|
||||
tags: array,intermediate
|
||||
firstSeen: 2018-07-18T20:49:07+03:00
|
||||
lastUpdated: 2020-10-22T20:24:44+03:00
|
||||
lastUpdated: 2021-10-13T19:29:39+02:00
|
||||
---
|
||||
|
||||
Finds all unique values of an array, based on a provided comparator function, starting from the right.
|
||||
|
||||
- Use `Array.prototype.reduceRight()` and `Array.prototype.some()` for an array containing only the last unique occurrence of each value, based on the comparator function, `fn`.
|
||||
- Use `Array.prototype.reduceRight()` and `Array.prototype.some()` to create an array containing only the last unique occurrence of each value, based on the comparator function, `fn`.
|
||||
- The comparator function takes two arguments: the values of the two elements being compared.
|
||||
|
||||
```js
|
||||
|
||||
Reference in New Issue
Block a user