Fully renamed and updated everything, tagged, built
This commit is contained in:
@ -13,15 +13,14 @@ Here's what you can do to help:
|
||||
### Snippet submission and Pull request guidelines
|
||||
|
||||
- **DO NOT MODIFY THE README.md FILE!** Make changes to individual snippet files. You can optionally run `npm run build-list` to update the README.md file automatically, based on the changes you have made.
|
||||
- **Snippet filenames** must correspond to the title of the snippet. For example, if your snippet is titled `### Awesome snippet` the filename should be `awesome-snippet.md`.
|
||||
- Use `kebab-case`, not `snake_case`.
|
||||
- **Snippet filenames** must correspond to the title of the snippet. For example, if your snippet is titled `### awesomeSnippet` the filename should be `awesomeSnippet.md`.
|
||||
- Use `camelCase`, not `kebab-case` or `snake_case`.
|
||||
- Avoid capitalization of words, except if the whole word is capitalized (e.g. `URL` should be capitalized in the filename and the snippet title).
|
||||
- If there are parentheses in the title, add them to the filename (e.g. `awesome-snippet-(extra-awesome).md` if your snippet's title is `Awesome snippet (extra awesome)`).
|
||||
- **Snippet titles** should have only the first letter of the first word capitalized. Certain words can be in capitals (e.g. `URL`, `RGB`), but this is on a per-snippet basis.
|
||||
- **Snippet titles** should have be the same as the name of the function that is present in the snippet.
|
||||
- All snippet titles must be prefixed with `###` and be at the very first line of your snippet.
|
||||
- Snippet titles must be unique (although if you cannot find a better title, just add some placeholder at the end of the filename and title and we will figure it out).
|
||||
- Follow snippet titles with an empty line.
|
||||
- **Snippet descriptions** must be short and to the point. Try to explain *how* the snippet works and what Javascript features are used. Remember to include what functions you are using and why.
|
||||
- **Snippet descriptions** must be short and to the point. Try to explain *what* the snippet does and *how* the snippet works and what Javascript features are used. Remember to include what functions you are using and why.
|
||||
- Follow snippet descriptions with an empty line.
|
||||
- **Snippet code** must be enclosed inside ` ```js ` and ` ``` `.
|
||||
- Remember to start your snippet's code on a new line below the opening backticks.
|
||||
|
||||
@ -55,7 +55,7 @@ try {
|
||||
for(let tag of [...new Set(Object.entries(tagDbData).map(t => t[1]))].filter(v => v).sort((a,b) => a.localeCompare(b))){
|
||||
output +=`### ${capitalize(tag, true)}\n`;
|
||||
for(let taggedSnippet of Object.entries(tagDbData).filter(v => v[1] === tag))
|
||||
output += `* [${taggedSnippet[0][0].toUpperCase() + taggedSnippet[0].replace(/-/g,' ').slice(1)}](#${taggedSnippet[0].replace(/\(/g,'').replace(/\)/g,'').toLowerCase()})\n`
|
||||
output += `* [\`${taggedSnippet[0]}\`](#${taggedSnippet[0].toLowerCase()})\n`
|
||||
output += '\n';
|
||||
}
|
||||
// Loop over tags and snippets to create the list of snippets
|
||||
|
||||
@ -1,4 +1,6 @@
|
||||
### Snippet title
|
||||
### functionName
|
||||
|
||||
Explain briefly what the snippet does.
|
||||
|
||||
Explain briefly how the snippet works.
|
||||
|
||||
|
||||
@ -1,9 +1,11 @@
|
||||
### JSON to date
|
||||
### JSONToDate
|
||||
|
||||
Converts a JSON object to a date.
|
||||
|
||||
Use `Date()`, to convert dates in JSON format to readable format (`dd/mm/yyyy`).
|
||||
|
||||
```js
|
||||
const jsonToDate = arr => {
|
||||
const JSONToDate = arr => {
|
||||
const dt = new Date(parseInt(arr.toString().substr(6)));
|
||||
return `${ dt.getDate() }/${ dt.getMonth() + 1 }/${ dt.getFullYear() }`
|
||||
};
|
||||
@ -1,9 +1,11 @@
|
||||
### Write JSON to file
|
||||
### JSONToFile
|
||||
|
||||
Writes a JSON object to a file.
|
||||
|
||||
Use `fs.writeFile()`, template literals and `JSON.stringify()` to write a `json` object to a `.json` file.
|
||||
|
||||
```js
|
||||
const fs = require('fs');
|
||||
const jsonToFile = (obj, filename) => fs.writeFile(`${filename}.json`, JSON.stringify(obj, null, 2))
|
||||
const JSONToFile = (obj, filename) => fs.writeFile(`${filename}.json`, JSON.stringify(obj, null, 2))
|
||||
// jsonToFile({test: "is passed"}, 'testJsonFile') -> writes the object to 'testJsonFile.json'
|
||||
```
|
||||
@ -1,8 +1,10 @@
|
||||
### RGB to hexadecimal
|
||||
### RGBToHex
|
||||
|
||||
Converts the values of RGB components to a colorcode.
|
||||
|
||||
Convert given RGB parameters to hexadecimal string using bitwise left-shift operator (`<<`) and `toString(16)`, then `padStart(6,'0')` to get a 6-digit hexadecimal value.
|
||||
|
||||
```js
|
||||
const rgbToHex = (r, g, b) => ((r << 16) + (g << 8) + b).toString(16).padStart(6, '0');
|
||||
const RGBToHex = (r, g, b) => ((r << 16) + (g << 8) + b).toString(16).padStart(6, '0');
|
||||
// rgbToHex(255, 165, 1) -> 'ffa501'
|
||||
```
|
||||
@ -1,9 +1,11 @@
|
||||
### UUID generator
|
||||
### UUIDGenerator
|
||||
|
||||
Generates a UUID.
|
||||
|
||||
Use `crypto` API to generate a UUID, compliant with [RFC4122](https://www.ietf.org/rfc/rfc4122.txt) version 4.
|
||||
|
||||
```js
|
||||
const uuidGenerator = () =>
|
||||
const UUIDGenerator = () =>
|
||||
([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>
|
||||
(c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
|
||||
);
|
||||
@ -1,4 +1,6 @@
|
||||
### Anagrams of string (with duplicates)
|
||||
### anagrams
|
||||
|
||||
Generates all anagrams of a string (contains duplicates).
|
||||
|
||||
Use recursion.
|
||||
For each letter in the given string, create all the partial anagrams for the rest of its letters.
|
||||
|
||||
@ -1,8 +1,10 @@
|
||||
### Average of array of numbers
|
||||
### arrayAverage
|
||||
|
||||
Returns the average of an array of numbers.
|
||||
|
||||
Use `Array.reduce()` to add each value to an accumulator, initialized with a value of `0`, divide by the `length` of the array.
|
||||
|
||||
```js
|
||||
const average = arr => arr.reduce((acc, val) => acc + val, 0) / arr.length;
|
||||
const arrayAverage = arr => arr.reduce((acc, val) => acc + val, 0) / arr.length;
|
||||
// average([1,2,3]) -> 2
|
||||
```
|
||||
@ -1,4 +1,6 @@
|
||||
### Get max value from array
|
||||
### arrayMax
|
||||
|
||||
Returns the maximum value in an array.
|
||||
|
||||
Use `Math.max()` combined with the spread operator (`...`) to get the maximum value in the array.
|
||||
|
||||
@ -1,4 +1,6 @@
|
||||
### Get min value from array
|
||||
### arrayMin
|
||||
|
||||
Returns the maximum value in an array.
|
||||
|
||||
Use `Math.min()` combined with the spread operator (`...`) to get the minimum value in the array.
|
||||
|
||||
@ -1,8 +1,10 @@
|
||||
### Sum of array of numbers
|
||||
### arraySum
|
||||
|
||||
Returns the sum of an array of numbers.
|
||||
|
||||
Use `Array.reduce()` to add each value to an accumulator, initialized with a value of `0`.
|
||||
|
||||
```js
|
||||
const sumArrayNumbers = arr => arr.reduce((acc, val) => acc + val, 0);
|
||||
const arraySum = arr => arr.reduce((acc, val) => acc + val, 0);
|
||||
// sum([1,2,3,4]) -> 10
|
||||
```
|
||||
@ -1,4 +1,6 @@
|
||||
### Bottom visible
|
||||
### bottomVisible
|
||||
|
||||
Returns `true` if the bottom of the page is visible, `false` otherwise.
|
||||
|
||||
Use `scrollY`, `scrollHeight` and `clientHeight` to determine if the bottom of the page is visible.
|
||||
|
||||
@ -1,4 +1,6 @@
|
||||
### Capitalize first letter
|
||||
### Capitalize
|
||||
|
||||
Capitalizes the first letter of a string.
|
||||
|
||||
Use destructuring and `toUpperCase()` to capitalize first letter, `...rest` to get array of characters after first letter and then `Array.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 lower case.
|
||||
|
||||
@ -1,4 +1,6 @@
|
||||
### Capitalize first letter of every word
|
||||
### capitalizeEveryWord
|
||||
|
||||
Capitalizes the first letter of every word in a string.
|
||||
|
||||
Use `replace()` to match the first character of each word and `toUpperCase()` to capitalize it.
|
||||
|
||||
@ -1,4 +1,6 @@
|
||||
### Chain asynchronous functions
|
||||
### chainAsync
|
||||
|
||||
Chains asynchronous functions.
|
||||
|
||||
Loop through an array of functions containing asynchronous events, calling `next` when each asynchronous event has completed.
|
||||
|
||||
@ -1,4 +1,6 @@
|
||||
### Chunk array
|
||||
### chunk
|
||||
|
||||
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.slice()` to map each element of the new array to a chunk the length of `size`.
|
||||
|
||||
@ -1,4 +1,6 @@
|
||||
### Clean JSON object
|
||||
### cleanObj
|
||||
|
||||
Removes any properties except the ones specified from a JSON object.
|
||||
|
||||
Use `Object.keys()` method to loop over given json object and deleting keys that are not `include`d in given array.
|
||||
also if you give it a special key(`childIndicator`) it will search deeply inside it to apply function to inner objects too.
|
||||
@ -1,4 +1,6 @@
|
||||
### Collatz algorithm
|
||||
### collatz
|
||||
|
||||
Applies the Collatz algorithm.
|
||||
|
||||
If `n` is even, return `n/2`. Otherwise return `3n+1`.
|
||||
|
||||
|
||||
@ -1,4 +1,6 @@
|
||||
### Compact
|
||||
### compact
|
||||
|
||||
Removes falsey values from an array.
|
||||
|
||||
Use `Array.filter()` to filter out falsey values (`false`, `null`, `0`, `""`, `undefined`, and `NaN`).
|
||||
|
||||
|
||||
@ -1,4 +1,6 @@
|
||||
### Compose functions
|
||||
### compose
|
||||
|
||||
Performs right-to-left function composition.
|
||||
|
||||
Use `Array.reduce()` to perform right-to-left function composition.
|
||||
The last (rightmost) function can accept one or more arguments; the remaining functions must be unary.
|
||||
|
||||
@ -1,4 +1,6 @@
|
||||
### Count occurrences of a value in array
|
||||
### countOccurrences
|
||||
|
||||
Counts the occurences of a value in an array.
|
||||
|
||||
Use `Array.reduce()` to increment a counter each time you encounter the specific value inside the array.
|
||||
|
||||
@ -1,8 +1,10 @@
|
||||
### Current URL
|
||||
### currentURL
|
||||
|
||||
Returns the current URL.
|
||||
|
||||
Use `window.location.href` to get current URL.
|
||||
|
||||
```js
|
||||
const currentUrl = () => window.location.href;
|
||||
const currentURL = () => window.location.href;
|
||||
// currentUrl() -> 'https://google.com'
|
||||
```
|
||||
|
||||
@ -1,4 +1,6 @@
|
||||
### Curry
|
||||
### curry
|
||||
|
||||
Curries a function.
|
||||
|
||||
Use recursion.
|
||||
If the number of provided arguments (`args`) is sufficient, call the passed function `f`.
|
||||
|
||||
@ -1,4 +1,6 @@
|
||||
### Deep flatten array
|
||||
### deepFlatten
|
||||
|
||||
Deep flattens an array.
|
||||
|
||||
Use recursion.
|
||||
Use `Array.concat()` with an empty array (`[]`) and the spread operator (`...`) to flatten an array.
|
||||
@ -1,4 +1,6 @@
|
||||
### Array difference
|
||||
### difference
|
||||
|
||||
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`.
|
||||
|
||||
|
||||
@ -1,4 +1,6 @@
|
||||
### Number to array of digits
|
||||
### digitize
|
||||
|
||||
Converts a number to an array of digits.
|
||||
|
||||
Convert the number to a string, using spread operators in ES6(`[...string]`) build an array.
|
||||
Use `Array.map()` and `parseInt()` to transform each value to an integer.
|
||||
@ -1,4 +1,6 @@
|
||||
### Distance between two points
|
||||
### distance
|
||||
|
||||
Returns the distance between two points.
|
||||
|
||||
Use `Math.hypot()` to calculate the Euclidean distance between two points.
|
||||
|
||||
|
||||
@ -1,8 +1,10 @@
|
||||
### Unique values of array
|
||||
### distinctValuesOfArray
|
||||
|
||||
Returns all the distinct values of an array.
|
||||
|
||||
Use ES6 `Set` and the `...rest` operator to discard all duplicated values.
|
||||
|
||||
```js
|
||||
const uniqueValuesOfArray = arr => [...new Set(arr)];
|
||||
const distinctValuesOfArray = arr => [...new Set(arr)];
|
||||
// unique([1,2,2,3,4,4,5]) -> [1,2,3,4,5]
|
||||
```
|
||||
@ -1,4 +1,6 @@
|
||||
### Drop elements in array
|
||||
### dropElements
|
||||
|
||||
Removes elements in an array until the passed function returns `true`. Returns the remaining elements in the array.
|
||||
|
||||
Loop through the array, using `Array.shift()` to drop the first element of the array until the returned value from the function is `true`.
|
||||
Returns the remaining elements.
|
||||
@ -1,4 +1,6 @@
|
||||
### Element is visible in viewport
|
||||
### elementIsVisibleInViewport
|
||||
|
||||
Returns `true` if the element specified is visible in the viewport, `false` otherwise.
|
||||
|
||||
Use `Element.getBoundingClientRect()` and the `window.inner(Width|Height)` values
|
||||
to determine if a given element is visible in the viewport.
|
||||
@ -1,4 +1,6 @@
|
||||
### Escape regular expression
|
||||
### escapeRegExp
|
||||
|
||||
Escapes a string to use in a regular expression.
|
||||
|
||||
Use `replace()` to escape special characters.
|
||||
|
||||
@ -1,4 +1,6 @@
|
||||
### Take every nth element
|
||||
### everyNth
|
||||
|
||||
Returns every nth element in an array.
|
||||
|
||||
Use `Array.filter()` to create a new array that contains every nth element of a given array.
|
||||
|
||||
@ -1,6 +1,8 @@
|
||||
### 3-digit hexcode to 6-digit hexcode
|
||||
### extendHex
|
||||
|
||||
Use `Array.map()`, `split()` and `Array.join()` to join the mapped array for converting a three-digit RGB notated hexadecimal color-code to the six-digit form.
|
||||
Extends a 3-digit color code to a 6-digit color code.
|
||||
|
||||
Use `Array.map()`, `split()` and `Array.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.
|
||||
```js
|
||||
const extendHex = shortHex =>
|
||||
@ -1,4 +1,6 @@
|
||||
### Factorial
|
||||
### factorial
|
||||
|
||||
Calculates the factorial of a number.
|
||||
|
||||
Use recursion.
|
||||
If `n` is less than or equal to `1`, return `1`.
|
||||
|
||||
@ -1,4 +1,6 @@
|
||||
### Fibonacci array generator
|
||||
### fibonacci
|
||||
|
||||
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`).
|
||||
Use `Array.reduce()` to add values into the array, using the sum of the last two values, except for the first two.
|
||||
|
||||
@ -1,4 +1,6 @@
|
||||
### Filter out non-unique values in an array
|
||||
### filterNonUnique
|
||||
|
||||
Filters out the non-unique values in an array.
|
||||
|
||||
Use `Array.filter()` for an array containing only the unique values.
|
||||
|
||||
@ -1,4 +1,6 @@
|
||||
### Flatten array
|
||||
### flatten
|
||||
|
||||
Flattens an array.
|
||||
|
||||
Use `Array.reduce()` to get all elements inside the array and `concat()` to flatten them.
|
||||
|
||||
|
||||
@ -1,4 +1,6 @@
|
||||
### Flatten array up to depth
|
||||
### flattenDepth
|
||||
|
||||
Flattens an array up to the specified depth.
|
||||
|
||||
Use recursion, decrementing `depth` by 1 for each level of depth.
|
||||
Use `Array.reduce()` and `Array.concat()` to merge elements or arrays.
|
||||
@ -1,7 +1,9 @@
|
||||
### Convert string from camelcase
|
||||
### fromCamelCase
|
||||
|
||||
Converts a string from camelcase.
|
||||
|
||||
Use `replace()` to remove underscores, hyphens and spaces and convert words to camelcase.
|
||||
Omit the scond argument to use a default separator of '_'.
|
||||
Omit the scond argument to use a default separator of `_`.
|
||||
|
||||
```js
|
||||
const fromCamelCase = (str, separator = '_') =>
|
||||
@ -1,4 +1,6 @@
|
||||
### Log function name
|
||||
### functionName
|
||||
|
||||
Logs the name of a function.
|
||||
|
||||
Use `console.debug()` and the `name` property of the passed method to log the method's name to the `debug` channel of the console.
|
||||
|
||||
@ -1,10 +1,12 @@
|
||||
### Greatest common divisor (GCD)
|
||||
### gcd
|
||||
|
||||
Calculates the greatest common divisor between two numbers.
|
||||
|
||||
Use recursion.
|
||||
Base case is when `y` equals `0`. In this case, return `x`.
|
||||
Otherwise, return the GCD of `y` and the remainder of the division `x/y`.
|
||||
|
||||
```js
|
||||
const greatestCommonDivisor = (x, y) => !y ? x : gcd(y, x % y);
|
||||
const gcd = (x, y) => !y ? x : gcd(y, x % y);
|
||||
// gcd (8, 36) -> 4
|
||||
```
|
||||
@ -1,4 +1,6 @@
|
||||
### Get days difference between dates
|
||||
### getDaysDiffBetweenDates
|
||||
|
||||
Returns the difference (in days) between two dates.
|
||||
|
||||
Calculate the difference (in days) between to `Date` objects.
|
||||
|
||||
@ -1,4 +1,6 @@
|
||||
### Get scroll position
|
||||
### getScrollPosition
|
||||
|
||||
Returns the scroll position of the current page.
|
||||
|
||||
Use `pageXOffset` and `pageYOffset` if they are defined, otherwise `scrollLeft` and `scrollTop`.
|
||||
You can omit `el` to use a default value of `window`.
|
||||
@ -1,4 +1,6 @@
|
||||
### Get native type of value
|
||||
### getType
|
||||
|
||||
Returns the native type of a value.
|
||||
|
||||
Returns lower-cased constructor name of value, "undefined" or "null" if value is undefined or null
|
||||
|
||||
@ -1,10 +1,12 @@
|
||||
### URL parameters
|
||||
### getURLParameters
|
||||
|
||||
Returns an object containing the parameters of the current URL.
|
||||
|
||||
Use `match()` with an appropriate regular expression to get all key-value pairs, `Array.reduce()` to map and combine them into a single object.
|
||||
Pass `location.search` as the argument to apply to the current `url`.
|
||||
|
||||
```js
|
||||
const getUrlParameters = url =>
|
||||
const getURLParameters = url =>
|
||||
url.match(/([^?=&]+)(=([^&]*))/g).reduce(
|
||||
(a, v) => (a[v.slice(0, v.indexOf('='))] = v.slice(v.indexOf('=') + 1), a), {}
|
||||
);
|
||||
@ -1,4 +1,6 @@
|
||||
### Group by
|
||||
### groupBy
|
||||
|
||||
Groups the element 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.reduce()` to create an object, where the keys are produced from the mapped results.
|
||||
@ -1,4 +1,6 @@
|
||||
### Hamming distance
|
||||
### hammingDistance
|
||||
|
||||
Calculates the Hamming distance between two values.
|
||||
|
||||
Use XOR operator (`^`) to find the bit difference between the two numbers, convert to binary string using `toString(2)`.
|
||||
Count and return the number of `1`s in the string, using `match(/1/g)`.
|
||||
@ -1,4 +1,6 @@
|
||||
### Head of list
|
||||
### head
|
||||
|
||||
Returns the head of a list.
|
||||
|
||||
Use `arr[0]` to return the first element of the passed array.
|
||||
|
||||
|
||||
@ -1,9 +1,11 @@
|
||||
### Hexcode to RGB
|
||||
### hexToRGB
|
||||
|
||||
Converts a colorcode to a `rgb()` string.
|
||||
|
||||
Use bitwise right-shift operator and mask bits with `&` (and) operator to convert a hexadecimal color code (prefixed with `#`) to a string with the RGB values.
|
||||
|
||||
```js
|
||||
const hexToRgb = hex => {
|
||||
const hexToRGB = hex => {
|
||||
const h = parseInt(hex.slice(1), 16);
|
||||
return `rgb(${h >> 16}, ${(h & 0x00ff00) >> 8}, ${h & 0x0000ff})`;
|
||||
}
|
||||
@ -1,4 +1,6 @@
|
||||
### Initial of list
|
||||
### initial
|
||||
|
||||
Returns all the elements of an array except the last one.
|
||||
|
||||
Use `arr.slice(0,-1)`to return all but the last element of the array.
|
||||
|
||||
|
||||
@ -1,10 +1,12 @@
|
||||
### Initialize array with range
|
||||
### initializeArrayWithRange
|
||||
|
||||
Initialized an array containing the numbers in the specified range.
|
||||
|
||||
Use `Array(end-start)` to create an array of the desired length, `Array.map()` to fill with the desired values in a range.
|
||||
You can omit `start` to use a default value of `0`.
|
||||
|
||||
```js
|
||||
const initializeArrayRange = (end, start = 0) =>
|
||||
const initializeArrayWithRange = (end, start = 0) =>
|
||||
Array.from({ length: end - start }).map((v, i) => i + start);
|
||||
// initializeArrayRange(5) -> [0,1,2,3,4]
|
||||
```
|
||||
@ -1,9 +1,11 @@
|
||||
### Initialize array with values
|
||||
### initializeArrayWithValues
|
||||
|
||||
Initializes and fills an array with the specified values.
|
||||
|
||||
Use `Array(n)` to create an array of the desired length, `fill(v)` to fill it with the desired values.
|
||||
You can omit `value` to use a default value of `0`.
|
||||
|
||||
```js
|
||||
const initializeArray = (n, value = 0) => Array(n).fill(value);
|
||||
const initializeArrayWithValues = (n, value = 0) => Array(n).fill(value);
|
||||
// initializeArray(5, 2) -> [2,2,2,2,2]
|
||||
```
|
||||
@ -1,4 +1,6 @@
|
||||
### Array intersection
|
||||
### intersection
|
||||
|
||||
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`.
|
||||
|
||||
|
||||
@ -1,4 +1,6 @@
|
||||
### Is array
|
||||
### isArray
|
||||
|
||||
Checks if the given argument is an array.
|
||||
|
||||
Use `Array.isArray()` to check if a value is classified as an array.
|
||||
|
||||
@ -1,4 +1,6 @@
|
||||
### Is boolean
|
||||
### isBoolean
|
||||
|
||||
Checks if the given argument is a native boolean element.
|
||||
|
||||
Use `typeof` to check if a value is classified as a boolean primitive.
|
||||
|
||||
@ -1,4 +1,6 @@
|
||||
### Divisible by number
|
||||
### isDivisible
|
||||
|
||||
Checks if the first numeric argument is divisible by the second one.
|
||||
|
||||
Use the modulo operator (`%`) to check if the remainder is equal to `0`.
|
||||
|
||||
@ -1,4 +1,6 @@
|
||||
### Even or odd number
|
||||
### isEven
|
||||
|
||||
Returns `true` if the given number is even, `false` otherwise.
|
||||
|
||||
Checks whether a number is odd or even using the modulo (`%`) operator.
|
||||
Returns `true` if the number is even, `false` if the number is odd.
|
||||
@ -1,4 +1,6 @@
|
||||
### Is function
|
||||
### isFunction
|
||||
|
||||
Checks if the given argument is a function.
|
||||
|
||||
Use `typeof` to check if a value is classified as a function primitive.
|
||||
|
||||
@ -1,4 +1,6 @@
|
||||
### Is number
|
||||
### isNumber
|
||||
|
||||
Checks if the given argument is a number.
|
||||
|
||||
Use `typeof` to check if a value is classified as a number primitive.
|
||||
|
||||
@ -1,4 +1,6 @@
|
||||
### Is string
|
||||
### isString
|
||||
|
||||
Checks if the given argument is a string.
|
||||
|
||||
Use `typeof` to check if a value is classified as a string primitive.
|
||||
|
||||
@ -1,4 +1,6 @@
|
||||
### Is symbol
|
||||
### isSymbol
|
||||
|
||||
Checks if the given argument is a symbol.
|
||||
|
||||
Use `typeof` to check if a value is classified as a symbol primitive.
|
||||
|
||||
@ -1,8 +1,10 @@
|
||||
### Last of list
|
||||
### last
|
||||
|
||||
Returns the last element in an array.
|
||||
|
||||
Use `arr.length - 1` to compute index of the last element of the given array and returning it.
|
||||
|
||||
```js
|
||||
const lastOfArray = arr => arr[arr.length - 1];
|
||||
const last = arr => arr[arr.length - 1];
|
||||
// last([1,2,3]) -> 3
|
||||
```
|
||||
@ -1,10 +1,12 @@
|
||||
### Least common multiple (LCM)
|
||||
### lcm
|
||||
|
||||
Returns the least common multiple of two numbers.
|
||||
|
||||
Use the greatest common divisor (GCD) formula and `Math.abs()` to determine the least common multiple.
|
||||
The GCD formula uses recursion.
|
||||
|
||||
```js
|
||||
const leastCommonMultiple = (x,y) => {
|
||||
const lcm = (x,y) => {
|
||||
const gcd = (x, y) => !y ? x : gcd(y, x % y);
|
||||
return Math.abs(x*y)/(gcd(x,y));
|
||||
};
|
||||
@ -1,4 +1,6 @@
|
||||
### Median of array of numbers
|
||||
### median
|
||||
|
||||
Returns the median of an array of numbers.
|
||||
|
||||
Find the middle of the array, use `Array.sort()` to sort the values.
|
||||
Return the number at the midpoint if `length` is odd, otherwise the average of the two middle numbers.
|
||||
@ -1,4 +1,6 @@
|
||||
### Nth element of array
|
||||
### nthElement
|
||||
|
||||
Returns the nth element of an array.
|
||||
|
||||
Use `Array.slice()` to get an array containing the nth element at the first place.
|
||||
If the index is out of bounds, return `[]`.
|
||||
@ -1,4 +1,6 @@
|
||||
### Object from key-value pairs
|
||||
### objectFromPairs
|
||||
|
||||
Creates an object from the given key-value pairs.
|
||||
|
||||
Use `Array.reduce()` to create and combine key-value pairs.
|
||||
|
||||
@ -1,4 +1,6 @@
|
||||
### Object to key-value pairs
|
||||
### objectToPairs
|
||||
|
||||
Creates an array of key-value pair arrays from an object.
|
||||
|
||||
Use `Object.keys()` and `Array.map()` to iterate over the object's keys and produce an array with key-value pairs.
|
||||
|
||||
@ -1,4 +1,6 @@
|
||||
### Check for palindrome
|
||||
### palindrome
|
||||
|
||||
Returns `true` if the given string is a palindrome, `false` otherwise.
|
||||
|
||||
Convert string `toLowerCase()` and use `replace()` to remove non-alphanumeric characters from it.
|
||||
Then, `split('')` into individual characters, `reverse()`, `join('')` and compare to the original, unreversed string, after converting it `tolowerCase()`.
|
||||
|
||||
@ -1,7 +1,8 @@
|
||||
### Percentile
|
||||
### percentile
|
||||
|
||||
Use `Array.reduce()` to calculate how many numbers are below the value and how many are the same value and
|
||||
apply the percentile formula.
|
||||
Uses the percentile formula to calculate how many numbers in the given array are less or equal to the given value.
|
||||
|
||||
Use `Array.reduce()` to calculate how many numbers are below the value and how many are the same value and apply the percentile formula.
|
||||
|
||||
```js
|
||||
const percentile = (arr, val) =>
|
||||
|
||||
@ -1,10 +1,11 @@
|
||||
### Pick
|
||||
### pick
|
||||
|
||||
Use `Array.reduce()` to convert the filtered/picked keys back to a object with the corresponding key:value pair if the key exist in the obj.
|
||||
Picks the key-value pairs corresponding to the given keys from an object.
|
||||
|
||||
Use `Array.reduce()` to convert the filtered/picked keys back to a object with the corresponding key-value pair if the key exist in the obj.
|
||||
|
||||
```js
|
||||
const pick = (obj, arr) =>
|
||||
arr.reduce((acc, curr) => (curr in obj && (acc[curr] = obj[curr]), acc), {});
|
||||
// pick({ 'a': 1, 'b': '2', 'c': 3 }, ['a', 'c']) -> { 'a': 1, 'c': 3 }
|
||||
// pick(object, ['a', 'c'])['a'] -> 1
|
||||
```
|
||||
|
||||
@ -1,4 +1,6 @@
|
||||
### Pipe functions
|
||||
### pipe
|
||||
|
||||
Performs left-to-right function composition.
|
||||
|
||||
Use `Array.reduce()` with the spread operator (`...`) to perform left-to-right function composition.
|
||||
The first (leftmost) function can accept one or more arguments; the remaining functions must be unary.
|
||||
@ -1,4 +1,6 @@
|
||||
### Powerset
|
||||
### powerset
|
||||
|
||||
Returns the powerset of a given array of numbers.
|
||||
|
||||
Use `Array.reduce()` combined with `Array.map()` to iterate over elements and combine into an array containing all combinations.
|
||||
|
||||
|
||||
@ -1,4 +1,6 @@
|
||||
### Promisify
|
||||
### promisify
|
||||
|
||||
Converts an asynchronous function to return a promise.
|
||||
|
||||
Use currying to return a function returning a `Promise` that calls the original function.
|
||||
Use the `...rest` operator to pass in all the parameters.
|
||||
|
||||
@ -1,4 +1,6 @@
|
||||
### Array pull (mutates array)
|
||||
### pull
|
||||
|
||||
Mutates the original array to filter out the values specified.
|
||||
|
||||
Use `Array.filter()` and `Array.includes()` to pull out the values that are not needed.
|
||||
Use `Array.length = 0` to mutate the passed in array by resetting it's length to zero and `Array.push()` to re-populate it with only the pulled values.
|
||||
|
||||
@ -1,4 +1,6 @@
|
||||
### Random integer in range
|
||||
### randomIntegerInRange
|
||||
|
||||
Returns a random integer in the specified range.
|
||||
|
||||
Use `Math.random()` to generate a random number and map it to the desired range, using `Math.floor()` to make it an integer.
|
||||
|
||||
@ -1,4 +1,6 @@
|
||||
### Random number in range
|
||||
### randomNumberInRange
|
||||
|
||||
Returns a random number in the specified range.
|
||||
|
||||
Use `Math.random()` to generate a random value, map it to the desired range using multiplication.
|
||||
|
||||
@ -1,4 +1,6 @@
|
||||
### Read file as array of lines
|
||||
### readFileLines
|
||||
|
||||
Returns an array of lines from the specified file.
|
||||
|
||||
Use `readFileSync` function in `fs` node package to create a `Buffer` from a file.
|
||||
convert buffer to string using `toString(encoding)` function.
|
||||
@ -6,7 +8,7 @@ creating an array from contents of file by `split`ing file content line by line(
|
||||
|
||||
```js
|
||||
const fs = require('fs');
|
||||
const readFileToArray = filename => fs.readFileSync(filename).toString('UTF8').split('\n');
|
||||
const readFileLines = filename => fs.readFileSync(filename).toString('UTF8').split('\n');
|
||||
/*
|
||||
contents of test.txt :
|
||||
line1
|
||||
@ -1,4 +1,6 @@
|
||||
### Redirect to URL
|
||||
### redirect
|
||||
|
||||
Redirects to a specified URL.
|
||||
|
||||
Use `window.location.href` or `window.location.replace()` to redirect to `url`.
|
||||
Pass a second argument to simulate a link click (`true` - default) or an HTTP redirect (`false`).
|
||||
@ -1,4 +1,6 @@
|
||||
### Array remove
|
||||
### remove
|
||||
|
||||
Removes elements from an array for which the given function returns `false`.
|
||||
|
||||
Use `Array.filter()` to find array elements that return truthy values and `Array.reduce()` to remove elements using `Array.splice()`.
|
||||
The `func` is invoked with three arguments (`value, index, array`).
|
||||
|
||||
@ -1,4 +1,6 @@
|
||||
### Reverse a string
|
||||
### reverseString
|
||||
|
||||
Reverses a string.
|
||||
|
||||
Use array destructuring and `Array.reverse()` to reverse the order of the characters in the string.
|
||||
Combine characters to get a string using `join('')`.
|
||||
@ -1,4 +1,6 @@
|
||||
### Round number to n digits
|
||||
### round
|
||||
|
||||
Rounds a number to a specified amount of digits.
|
||||
|
||||
Use `Math.round()` and template literals to round the number to the specified number of digits.
|
||||
Omit the second argument, `decimals` to round to an integer.
|
||||
@ -1,6 +1,8 @@
|
||||
### Run promises in series
|
||||
### runPromisesInSeries
|
||||
|
||||
Run an array of promises in series using `Array.reduce()` by creating a promise chain, where each promise returns the next promise when resolved.
|
||||
Runs an array of promises in series.
|
||||
|
||||
Use `Array.reduce()` to create a promise chain, where each promise returns the next promise when resolved.
|
||||
|
||||
```js
|
||||
const runPromisesInSeries = ps => ps.reduce((p, next) => p.then(next), Promise.resolve());
|
||||
@ -1,4 +1,6 @@
|
||||
### Array sample
|
||||
### sample
|
||||
|
||||
Returns a random element from an array.
|
||||
|
||||
Use `Math.random()` to generate a random number, multiply it with `length` and round it of to the nearest whole number using `Math.floor()`.
|
||||
This method also works with strings.
|
||||
|
||||
@ -1,4 +1,6 @@
|
||||
### Scroll to top
|
||||
### scrollToTop
|
||||
|
||||
Smooth-scrolls to the top of the page.
|
||||
|
||||
Get distance from top using `document.documentElement.scrollTop` or `document.body.scrollTop`.
|
||||
Scroll by a fraction of the distance from top. Use `window.requestAnimationFrame()` to animate the scrolling.
|
||||
@ -1,4 +1,6 @@
|
||||
### Shallow clone object
|
||||
### shallowClone
|
||||
|
||||
Creates a shallow clone of an object.
|
||||
|
||||
Use `Object.assign()` and an empty object (`{}`) to create a shallow clone of the original.
|
||||
|
||||
@ -1,8 +1,10 @@
|
||||
### Shuffle array
|
||||
### shuffle
|
||||
|
||||
Randomizes the order of the values of an array.
|
||||
|
||||
Use `Array.sort()` to reorder elements, using `Math.random()` in the comparator.
|
||||
|
||||
```js
|
||||
const shuffleArray = arr => arr.sort(() => Math.random() - 0.5);
|
||||
const shuffle = arr => arr.sort(() => Math.random() - 0.5);
|
||||
// shuffle([1,2,3]) -> [2,3,1]
|
||||
```
|
||||
@ -1,4 +1,6 @@
|
||||
### Similarity between arrays
|
||||
### similarity
|
||||
|
||||
Returns an array of elements that appear in both arrays.
|
||||
|
||||
Use `filter()` to remove values that are not part of `values`, determined using `includes()`.
|
||||
|
||||
|
||||
@ -1,4 +1,6 @@
|
||||
### Sleep
|
||||
### sleep
|
||||
|
||||
Delays the execution of an asynchronous function.
|
||||
|
||||
Delay executing part of an `async` function, by putting it to sleep, returning a `Promise`.
|
||||
|
||||
|
||||
@ -1,4 +1,6 @@
|
||||
### Sort characters in string (alphabetical)
|
||||
### sortCharactersInString
|
||||
|
||||
Alphabetically sorts the characters in a string.
|
||||
|
||||
Split the string using `split('')`, `Array.sort()` utilizing `localeCompare()`, recombine using `join('')`.
|
||||
|
||||
@ -1,4 +1,6 @@
|
||||
### Speech synthesis (experimental)
|
||||
### speechSynthesis
|
||||
|
||||
Performs speech synthesis (experimental).
|
||||
|
||||
Use `SpeechSynthesisUtterance.voice` and `window.speechSynthesis.getVoices()` to convert a message to speech.
|
||||
Use `window.speechSynthesis.speak()` to play the message.
|
||||
@ -1,4 +1,6 @@
|
||||
### Standard deviation
|
||||
### standardDeviation
|
||||
|
||||
Returns the standard deviation of an array of numbers.
|
||||
|
||||
Use `Array.reduce()` to calculate the mean, variance and the sum of the variance of the values, the variance of the values, then
|
||||
determine the standard deviation.
|
||||
@ -1,4 +1,6 @@
|
||||
### Array symmetric difference
|
||||
### symmetricDifference
|
||||
|
||||
Returns the symmetric difference between two arrays.
|
||||
|
||||
Create a `Set` from each array, then use `Array.filter()` on each of them to only keep values not contained in the other.
|
||||
|
||||
@ -1,9 +1,11 @@
|
||||
### Tail of list
|
||||
### tail
|
||||
|
||||
Returns all elements in an array except for the first one.
|
||||
|
||||
Return `arr.slice(1)` if the array's `length` is more than `1`, otherwise return the whole array.
|
||||
|
||||
```js
|
||||
const tailOfList = arr => arr.length > 1 ? arr.slice(1) : arr;
|
||||
const tail = arr => arr.length > 1 ? arr.slice(1) : arr;
|
||||
// tail([1,2,3]) -> [2,3]
|
||||
// tail([1]) -> [1]
|
||||
```
|
||||
@ -1,4 +1,6 @@
|
||||
### Take
|
||||
### take
|
||||
|
||||
Returns an array with n elements removed from the beggining.
|
||||
|
||||
Use `Array.slice()` to create a slice of the array with `n` elements taken from the beginning.
|
||||
|
||||
|
||||
@ -1,4 +1,6 @@
|
||||
### Take right
|
||||
### takeRight
|
||||
|
||||
Returns an array with n elements removed from the end.
|
||||
|
||||
Use `Array.slice()` to create a slice of the array with `n` elements taken from the end.
|
||||
|
||||
@ -1,13 +1,13 @@
|
||||
### Measure time taken by function
|
||||
### timeTaken
|
||||
|
||||
Measures the time taken by a function to execute.
|
||||
|
||||
Use `console.time()` and `console.timeEnd()` to measure the difference between the start and end times to determine how long the callback took to execute.
|
||||
|
||||
```js
|
||||
const timeTaken = callback => {
|
||||
console.time('timeTaken');
|
||||
const r = callback();
|
||||
console.timeEnd('timeTaken');
|
||||
return r;
|
||||
console.time('timeTaken'); const r = callback();
|
||||
console.timeEnd('timeTaken'); return r;
|
||||
};
|
||||
// timeTaken(() => Math.pow(2, 10)) -> 1024
|
||||
// (logged): timeTaken: 0.02099609375ms
|
||||
@ -1,4 +1,6 @@
|
||||
### Convert string to camelcase
|
||||
### toCamelCase
|
||||
|
||||
Converts a string to camelcase.
|
||||
|
||||
Use `replace()` to remove underscores, hyphens and spaces and convert words to camelcase.
|
||||
|
||||
@ -1,4 +1,6 @@
|
||||
### Convert to English date
|
||||
### toEnglishDate
|
||||
|
||||
Converts a date from American format to English format.
|
||||
|
||||
Use `Date.toISOString()`, `split('T')` and `replace()` to convert a date from American format to English format.
|
||||
Throws an error if the passed time cannot be converted to a date.
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user