Updated builder with links to top
This commit is contained in:
79
README.md
79
README.md
@ -7,7 +7,7 @@
|
||||
- Contributions welcome, please read the [contribution guide](CONTRIBUTING.md).
|
||||
- Snippets are written in ES6, use the [Babel transpiler](https://babeljs.io/) to ensure backwards-compatibility.
|
||||
|
||||
## Contents
|
||||
## Table of Contents
|
||||
|
||||
* [Anagrams of string (with duplicates)](#anagrams-of-string-with-duplicates)
|
||||
* [Array concatenation](#array-concatenation)
|
||||
@ -103,6 +103,7 @@ const anagrams = str => {
|
||||
// anagrams('abc') -> ['abc','acb','bac','bca','cab','cba']
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
### Array concatenation
|
||||
|
||||
Use `Array.concat()` to concatenate and array with any additional arrays and/or values, specified in `args`.
|
||||
@ -112,6 +113,7 @@ const arrayConcat = (arr, ...args) => arr.concat(...args);
|
||||
// arrayConcat([1], 2, [3], [[4]]) -> [1,2,3,[4]]
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
### Array difference
|
||||
|
||||
Create a `Set` from `b`, then use `Array.filter()` on `a` to only keep values not contained in `b`.
|
||||
@ -121,6 +123,7 @@ const difference = (a, b) => { const s = new Set(b); return a.filter(x => !s.has
|
||||
// difference([1,2,3], [1,2]) -> [3]
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
### Array intersection
|
||||
|
||||
Create a `Set` from `b`, then use `Array.filter()` on `a` to only keep values contained in `b`.
|
||||
@ -130,6 +133,7 @@ const intersection = (a, b) => { const s = new Set(b); return a.filter(x => s.ha
|
||||
// intersection([1,2,3], [4,3,2]) -> [2,3]
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
### Array union
|
||||
|
||||
Create a `Set` with all values of `a` and `b` and convert to an array.
|
||||
@ -139,6 +143,7 @@ const union = (a, b) => Array.from(new Set([...a, ...b]))
|
||||
// union([1,2,3], [4,3,2]) -> [1,2,3,4]
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
### Average of 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.
|
||||
@ -148,6 +153,7 @@ const average = arr => arr.reduce((acc, val) => acc + val, 0) / arr.length;
|
||||
// average([1,2,3]) -> 2
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
### Bottom visible
|
||||
|
||||
Use `scrollY`, `scrollHeight` and `clientHeight` to determine if the bottom of the page is visible.
|
||||
@ -158,6 +164,7 @@ const bottomVisible = _ =>
|
||||
// bottomVisible() -> true
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
### Capitalize first letter of every word
|
||||
|
||||
Use `replace()` to match the first character of each word and `toUpperCase()` to capitalize it.
|
||||
@ -167,6 +174,7 @@ const capitalizeEveryWord = str => str.replace(/\b[a-z]/g, char => char.toUpperC
|
||||
// capitalizeEveryWord('hello world!') -> 'Hello World!'
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
### Capitalize first letter
|
||||
|
||||
Use `slice(0,1)` and `toUpperCase()` to capitalize first letter, `slice(1)` to get the rest of the string.
|
||||
@ -178,6 +186,7 @@ const capitalize = (str, lowerRest = false) =>
|
||||
// capitalize('myName', true) -> 'Myname'
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
### Chain asynchronous functions
|
||||
|
||||
Loop through an array of functions containing asynchronous events, calling `next` when each asynchronous event has completed.
|
||||
@ -193,6 +202,7 @@ chainAsync([
|
||||
*/
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
### Check for palindrome
|
||||
|
||||
Convert string `toLowerCase()` and use `replace()` to remove non-alphanumeric characters from it.
|
||||
@ -206,6 +216,7 @@ const palindrome = str => {
|
||||
// palindrome('taco cat') -> true
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
### Chunk array
|
||||
|
||||
Use `Array.from()` to create a new array, that fits the number of chunks that will be produced.
|
||||
@ -218,6 +229,7 @@ const chunk = (arr, size) =>
|
||||
// chunk([1,2,3,4,5], 2) -> [[1,2],[3,4],5]
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
### Compact
|
||||
|
||||
Use `Array.filter()` to filter out falsey values (`false`, `null`, `0`, `""`, `undefined`, and `NaN`).
|
||||
@ -227,6 +239,7 @@ const compact = (arr) => arr.filter(v => v);
|
||||
// compact([0, 1, false, 2, '', 3, 'a', 'e'*23, NaN, 's', 34]) -> [ 1, 2, 3, 'a', 's', 34 ]
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
### Count occurrences of a value in array
|
||||
|
||||
Use `Array.reduce()` to increment a counter each time you encounter the specific value inside the array.
|
||||
@ -236,6 +249,7 @@ const countOccurrences = (arr, value) => arr.reduce((a, v) => v === value ? a +
|
||||
// countOccurrences([1,1,2,1,2,3], 1) -> 3
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
### Current URL
|
||||
|
||||
Use `window.location.href` to get current URL.
|
||||
@ -245,6 +259,7 @@ const currentUrl = _ => window.location.href;
|
||||
// currentUrl() -> 'https://google.com'
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
### Curry
|
||||
|
||||
Use recursion.
|
||||
@ -264,6 +279,7 @@ const curry = (f, arity = f.length, next) =>
|
||||
// curry(Math.min, 3)(10)(50)(2) -> 2
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
### Deep flatten array
|
||||
|
||||
Use recursion.
|
||||
@ -275,6 +291,7 @@ const deepFlatten = arr =>
|
||||
// deepFlatten([1,[2],[[3],4],5]) -> [1,2,3,4,5]
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
### Distance between two points
|
||||
|
||||
Use `Math.hypot()` to calculate the Euclidean distance between two points.
|
||||
@ -284,6 +301,7 @@ const distance = (x0, y0, x1, y1) => Math.hypot(x1 - x0, y1 - y0);
|
||||
// distance(1,1, 2,3) -> 2.23606797749979
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
### Divisible by number
|
||||
|
||||
Use the modulo operator (`%`) to check if the remainder is equal to `0`.
|
||||
@ -293,6 +311,7 @@ const isDivisible = (dividend, divisor) => dividend % divisor === 0;
|
||||
// isDivisible(6,3) -> true
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
### Drop elements in 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`.
|
||||
@ -306,6 +325,7 @@ const dropElements = (arr,func) => {
|
||||
// dropElements([1, 2, 3, 4], n => n >= 3) -> [3,4]
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
### Element is visible in viewport
|
||||
|
||||
Use `Element.getBoundingClientRect()` and the `window.inner(Width|Height)` values
|
||||
@ -326,6 +346,7 @@ const elementIsVisibleInViewport = (el, partiallyVisible = false) => {
|
||||
// elementIsInViewport(el, true) -> true (partially visible)
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
### Escape regular expression
|
||||
|
||||
Use `replace()` to escape special characters.
|
||||
@ -335,6 +356,7 @@ const escapeRegExp = str => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||
// escapeRegExp('(test)') -> \\(test\\)
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
### Even or odd number
|
||||
|
||||
Checks whether a number is odd or even using the modulo (`%`) operator.
|
||||
@ -345,6 +367,7 @@ const isEven = num => num % 2 === 0;
|
||||
// isEven(3) -> false
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
### Factorial
|
||||
|
||||
Use recursion.
|
||||
@ -356,6 +379,7 @@ const factorial = n => n <= 1 ? 1 : n * factorial(n - 1);
|
||||
// factorial(6) -> 720
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
### Fibonacci array generator
|
||||
|
||||
Create an empty array of the specific length, initializing the first two values (`0` and `1`).
|
||||
@ -367,6 +391,7 @@ const fibonacci = n =>
|
||||
// fibonacci(5) -> [0,1,1,2,3]
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
### Filter out non-unique values in an array
|
||||
|
||||
Use `Array.filter()` for an array containing only the unique values.
|
||||
@ -376,6 +401,7 @@ const filterNonUnique = arr => arr.filter(i => arr.indexOf(i) === arr.lastIndexO
|
||||
// filterNonUnique([1,2,2,3,4,4,5]) -> [1,3,5]
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
### Flatten array
|
||||
|
||||
Use `Array.reduce()` to get all elements inside the array and `concat()` to flatten them.
|
||||
@ -385,6 +411,7 @@ const flatten = arr => arr.reduce((a, v) => a.concat(v), []);
|
||||
// flatten([1,[2],3,4]) -> [1,2,3,4]
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
### Get max value from array
|
||||
|
||||
Use `Math.max()` combined with the spread operator (`...`) to get the maximum value in the array.
|
||||
@ -394,6 +421,7 @@ const arrayMax = arr => Math.max(...arr);
|
||||
// arrayMax([10, 1, 5]) -> 10
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
### Get min value from array
|
||||
|
||||
Use `Math.min()` combined with the spread operator (`...`) to get the minimum value in the array.
|
||||
@ -403,6 +431,7 @@ const arrayMin = arr => Math.min(...arr);
|
||||
// arrayMin([10, 1, 5]) -> 1
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
### Get native type of value
|
||||
|
||||
Returns lower-cased constructor name of value, "undefined" or "null" if value is undefined or null
|
||||
@ -413,6 +442,7 @@ const getType = v =>
|
||||
// getType(new Set([1,2,3])) -> "set"
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
### Get scroll position
|
||||
|
||||
Use `pageXOffset` and `pageYOffset` if they are defined, otherwise `scrollLeft` and `scrollTop`.
|
||||
@ -425,6 +455,7 @@ const getScrollPos = (el = window) =>
|
||||
// getScrollPos() -> {x: 0, y: 200}
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
### Greatest common divisor (GCD)
|
||||
|
||||
Use recursion.
|
||||
@ -436,6 +467,7 @@ const gcd = (x, y) => !y ? x : gcd(y, x % y);
|
||||
// gcd (8, 36) -> 4
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
### Group by
|
||||
|
||||
Use `Array.map()` to map the values of an array to a function or property name.
|
||||
@ -451,6 +483,7 @@ const groupBy = (arr, func) =>
|
||||
// groupBy(['one', 'two', 'three'], 'length') -> {3: ['one', 'two'], 5: ['three']}
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
### Hamming distance
|
||||
|
||||
Use XOR operator (`^`) to find the bit difference between the two numbers, convert to binary string using `toString(2)`.
|
||||
@ -462,6 +495,7 @@ const hammingDistance = (num1, num2) =>
|
||||
// hammingDistance(2,3) -> 1
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
### Head of list
|
||||
|
||||
Use `arr[0]` to return the first element of the passed array.
|
||||
@ -471,6 +505,7 @@ const head = arr => arr[0];
|
||||
// head([1,2,3]) -> 1
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
### Initial of list
|
||||
|
||||
Use `arr.slice(0,-1)`to return all but the last element of the array.
|
||||
@ -480,6 +515,7 @@ const initial = arr => arr.slice(0, -1);
|
||||
// initial([1,2,3]) -> [1,2]
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
### Initialize array with range
|
||||
|
||||
Use `Array(end-start)` to create an array of the desired length, `Array.map()` to fill with the desired values in a range.
|
||||
@ -491,6 +527,7 @@ const initializeArrayRange = (end, start = 0) =>
|
||||
// initializeArrayRange(5) -> [0,1,2,3,4]
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
### Initialize array with values
|
||||
|
||||
Use `Array(n)` to create an array of the desired length, `fill(v)` to fill it with the desired values.
|
||||
@ -501,6 +538,7 @@ const initializeArray = (n, value = 0) => Array(n).fill(value);
|
||||
// initializeArray(5, 2) -> [2,2,2,2,2]
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
### Is boolean
|
||||
|
||||
Use `typeof` to check if a value is classified as a boolean primitive.
|
||||
@ -511,6 +549,7 @@ const isBoolean = val => typeof val === 'boolean';
|
||||
// isBoolean(false) -> true
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
### Is boolean
|
||||
|
||||
Use `typeof` to check if a value is classified as a function primitive.
|
||||
@ -521,6 +560,7 @@ const isFunction = val => val && typeof val === 'function';
|
||||
// isFunction(x => x) -> true
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
### Is number
|
||||
|
||||
Use `typeof` to check if a value is classified as a number primitive.
|
||||
@ -531,6 +571,7 @@ const isNumber = val => typeof val === 'number';
|
||||
// isNumber(1) -> true
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
### Is string
|
||||
|
||||
Use `typeof` to check if a value is classified as a string primitive.
|
||||
@ -541,6 +582,7 @@ const isString = val => typeof val === 'string';
|
||||
// isString('10') -> true
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
### Is symbol
|
||||
|
||||
Use `typeof` to check if a value is classified as a symbol primitive.
|
||||
@ -551,6 +593,7 @@ const isSymbol = val => typeof val === 'symbol';
|
||||
// isSymbol(Symbol('x')) -> true
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
### Last of list
|
||||
|
||||
Use `arr.slice(-1)[0]` to get the last element of the given array.
|
||||
@ -560,6 +603,7 @@ const last = arr => arr.slice(-1)[0];
|
||||
// last([1,2,3]) -> 3
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
### Measure time taken by function
|
||||
|
||||
Use `performance.now()` to get start and end time for the function, `console.log()` the time taken.
|
||||
@ -574,6 +618,7 @@ const timeTaken = callback => {
|
||||
// timeTaken(() => Math.pow(2, 10)) -> 1024 (0.010000000009313226 logged in console)
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
### Median of array of numbers
|
||||
|
||||
Find the middle of the array, use `Array.sort()` to sort the values.
|
||||
@ -588,6 +633,7 @@ const median = arr => {
|
||||
// median([0,10,-2,7]) -> 3.5
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
### Object from key-value pairs
|
||||
|
||||
Use `Array.reduce()` to create and combine key-value pairs.
|
||||
@ -597,6 +643,7 @@ const objectFromPairs = arr => arr.reduce((a, v) => (a[v[0]] = v[1], a), {});
|
||||
// objectFromPairs([['a',1],['b',2]]) -> {a: 1, b: 2}
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
### Object to key-value pairs
|
||||
|
||||
Use `Object.keys()` and `Array.map()` to iterate over the object's keys and produce an array with key-value pairs.
|
||||
@ -606,6 +653,7 @@ const objectToPairs = obj => Object.keys(obj).map(k => [k, obj[k]]);
|
||||
// objectToPairs({a: 1, b: 2}) -> [['a',1],['b',2]])
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
### Ordinal suffix of number
|
||||
|
||||
Use the modulo operator (`%`) to find values of single and tens digits.
|
||||
@ -622,6 +670,7 @@ const toOrdinalSuffix = num => {
|
||||
// toOrdinalSuffix("123") -> "123rd"
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
### Percentile
|
||||
|
||||
Use `Array.reduce()` to calculate how many numbers are below the value and how many are the same value and
|
||||
@ -633,6 +682,7 @@ const percentile = (arr, val) =>
|
||||
// percentile([1,2,3,4,5,6,7,8,9,10], 6) -> 55
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
### 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.
|
||||
@ -644,6 +694,7 @@ const pick = (obj, arr) =>
|
||||
// pick(object, ['a', 'c'])['a'] -> 1
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
### Pipe
|
||||
|
||||
Use `Array.reduce()` to pass value through functions.
|
||||
@ -653,6 +704,7 @@ const pipe = (...funcs) => arg => funcs.reduce((acc, func) => func(acc), arg);
|
||||
// pipe(btoa, x => x.toUpperCase())("Test") -> "VGVZDA=="
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
### Powerset
|
||||
|
||||
Use `Array.reduce()` combined with `Array.map()` to iterate over elements and combine into an array containing all combinations.
|
||||
@ -663,6 +715,7 @@ const powerset = arr =>
|
||||
// powerset([1,2]) -> [[], [1], [2], [2,1]]
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
### Promisify
|
||||
|
||||
Use currying to return a function returning a `Promise` that calls the original function.
|
||||
@ -681,6 +734,7 @@ const promisify = func =>
|
||||
// delay(2000).then(() => console.log('Hi!')) -> Promise resolves after 2s
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
### Random integer in range
|
||||
|
||||
Use `Math.random()` to generate a random number and map it to the desired range, using `Math.floor()` to make it an integer.
|
||||
@ -690,6 +744,7 @@ const randomIntegerInRange = (min, max) => Math.floor(Math.random() * (max - min
|
||||
// randomIntegerInRange(0, 5) -> 2
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
### Random number in range
|
||||
|
||||
Use `Math.random()` to generate a random value, map it to the desired range using multiplication.
|
||||
@ -699,6 +754,7 @@ const randomInRange = (min, max) => Math.random() * (max - min) + min;
|
||||
// randomInRange(2,10) -> 6.0211363285087005
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
### Redirect to URL
|
||||
|
||||
Use `window.location.href` or `window.location.replace()` to redirect to `url`.
|
||||
@ -710,6 +766,7 @@ const redirect = (url, asLink = true) =>
|
||||
// redirect('https://google.com')
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
### Reverse a string
|
||||
|
||||
Use array destructuring and `Array.reverse()` to reverse the order of the characters in the string.
|
||||
@ -720,6 +777,7 @@ const reverseString = str => [...str].reverse().join('');
|
||||
// reverseString('foobar') -> 'raboof'
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
### RGB to hexadecimal
|
||||
|
||||
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.
|
||||
@ -729,6 +787,7 @@ const rgbToHex = (r, g, b) => ((r << 16) + (g << 8) + b).toString(16).padStart(6
|
||||
// rgbToHex(255, 165, 1) -> 'ffa501'
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
### Run promises in series
|
||||
|
||||
Run an array of promises in series using `Array.reduce()` by creating a promise chain, where each promise returns the next promise when resolved.
|
||||
@ -739,6 +798,7 @@ const series = ps => ps.reduce((p, next) => p.then(next), Promise.resolve());
|
||||
// series([() => delay(1000), () => delay(2000)]) -> executes each promise sequentially, taking a total of 3 seconds to complete
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
### Scroll to top
|
||||
|
||||
Get distance from top using `document.documentElement.scrollTop` or `document.body.scrollTop`.
|
||||
@ -755,6 +815,7 @@ const scrollToTop = _ => {
|
||||
// scrollToTop()
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
### Shuffle array
|
||||
|
||||
Use `Array.sort()` to reorder elements, using `Math.random()` in the comparator.
|
||||
@ -764,6 +825,7 @@ const shuffle = arr => arr.sort(() => Math.random() - 0.5);
|
||||
// shuffle([1,2,3]) -> [2,3,1]
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
### Similarity between arrays
|
||||
|
||||
Use `filter()` to remove values that are not part of `values`, determined using `includes()`.
|
||||
@ -773,6 +835,7 @@ const similarity = (arr, values) => arr.filter(v => values.includes(v));
|
||||
// similarity([1,2,3], [1,2,4]) -> [1,2]
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
### Sleep
|
||||
|
||||
Delay executing part of an `async` function, by putting it to sleep, returning a `Promise`.
|
||||
@ -788,6 +851,7 @@ async function sleepyWork() {
|
||||
*/
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
### Sort characters in string (alphabetical)
|
||||
|
||||
Split the string using `split('')`, `Array.sort()` utilizing `localeCompare()`, recombine using `join('')`.
|
||||
@ -798,6 +862,7 @@ const sortCharactersInString = str =>
|
||||
// sortCharactersInString('cabbage') -> 'aabbceg'
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
### Standard deviation
|
||||
|
||||
Use `Array.reduce()` to calculate the mean, variance and the sum of the variance of the values, the variance of the values, then
|
||||
@ -816,6 +881,7 @@ const standardDeviation = (arr, usePopulation = false) => {
|
||||
// standardDeviation([10,2,38,23,38,23,21], true) -> 12.29899614287479 (population)
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
### Sum of array of numbers
|
||||
|
||||
Use `Array.reduce()` to add each value to an accumulator, initialized with a value of `0`.
|
||||
@ -825,6 +891,7 @@ const sum = arr => arr.reduce((acc, val) => acc + val, 0);
|
||||
// sum([1,2,3,4]) -> 10
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
### Swap values of two variables
|
||||
|
||||
Use array destructuring to swap values between two variables.
|
||||
@ -834,6 +901,7 @@ Use array destructuring to swap values between two variables.
|
||||
// [x, y] = [y, x]
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
### Tail of list
|
||||
|
||||
Return `arr.slice(1)` if the array's `length` is more than `1`, otherwise return the whole array.
|
||||
@ -844,6 +912,7 @@ const tail = arr => arr.length > 1 ? arr.slice(1) : arr;
|
||||
// tail([1]) -> [1]
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
### Take
|
||||
|
||||
Use `Array.slice()` to create a slice of the array with `n` elements taken from the beginning.
|
||||
@ -855,6 +924,7 @@ const take = (arr, n = 1) => arr.slice(0, n);
|
||||
// take([1, 2, 3], 0) -> []
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
### Truncate a String
|
||||
|
||||
Determine if the string's `length` is greater than `num`.
|
||||
@ -866,6 +936,7 @@ const truncate = (str, num) =>
|
||||
// truncate('boomerang', 7) -> 'boom...'
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
### Unique values of array
|
||||
|
||||
Use ES6 `Set` and the `...rest` operator to discard all duplicated values.
|
||||
@ -875,6 +946,7 @@ const unique = arr => [...new Set(arr)];
|
||||
// unique([1,2,2,3,4,4,5]) -> [1,2,3,4,5]
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
### URL parameters
|
||||
|
||||
Use `match()` with an appropriate regular expression to get all key-value pairs, `Array.reduce()` to map and combine them into a single object.
|
||||
@ -888,6 +960,7 @@ const getUrlParameters = url =>
|
||||
// getUrlParameters('http://url.com/page?name=Adam&surname=Smith') -> {name: 'Adam', surname: 'Smith'}
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
### UUID generator
|
||||
|
||||
Use `crypto` API to generate a UUID, compliant with [RFC4122](https://www.ietf.org/rfc/rfc4122.txt) version 4.
|
||||
@ -900,6 +973,7 @@ const uuid = _ =>
|
||||
// uuid() -> '7982fcfe-5721-4632-bede-6000885be57d'
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
### Validate email
|
||||
|
||||
Use a regular experssion to check if the email is valid.
|
||||
@ -911,6 +985,7 @@ const validateEmail = str =>
|
||||
// validateEmail(mymail@gmail.com) -> true
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
### Validate number
|
||||
|
||||
Use `!isNaN` in combination with `parseFloat()` to check if the argument is a number.
|
||||
@ -922,6 +997,7 @@ const validateNumber = n => !isNaN(parseFloat(n)) && isFinite(n) && Number(n) ==
|
||||
// validateNumber('10') -> true
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
### Value or default
|
||||
|
||||
Returns value, or default value if passed value is `falsy`.
|
||||
@ -931,6 +1007,7 @@ const valueOrDefault = (value, d) => value || d;
|
||||
// valueOrDefault(NaN, 30) -> 30
|
||||
```
|
||||
|
||||
[⬆ back to top](#table-of-contents)
|
||||
## Credits
|
||||
|
||||
*Icons made by [Smashicons](https://www.flaticon.com/authors/smashicons) from [www.flaticon.com](https://www.flaticon.com/) is licensed by [CC 3.0 BY](http://creativecommons.org/licenses/by/3.0/).*
|
||||
|
||||
@ -45,7 +45,7 @@ try {
|
||||
output += `* [${snippet[0][0].toUpperCase() + snippet[0].replace(/-/g,' ').slice(1,snippet[0].length-3)}](#${snippet[0].slice(0,snippet[0].length-3).replace(/\(/g,'').replace(/\)/g,'').toLowerCase()})\n`
|
||||
output += '\n';
|
||||
for(var snippet of Object.entries(snippets))
|
||||
output += `${snippet[1]+'\n'}`;
|
||||
output += `${snippet[1]+'\n[⬆ back to top](#table-of-contents)\n'}`;
|
||||
output += `${endPart+'\n'}`;
|
||||
fs.writeFileSync('README.md', output);
|
||||
}
|
||||
|
||||
@ -7,4 +7,4 @@
|
||||
- Contributions welcome, please read the [contribution guide](CONTRIBUTING.md).
|
||||
- Snippets are written in ES6, use the [Babel transpiler](https://babeljs.io/) to ensure backwards-compatibility.
|
||||
|
||||
## Contents
|
||||
## Table of Contents
|
||||
|
||||
Reference in New Issue
Block a user