Merge branch 'master' into master
This commit is contained in:
@ -3,6 +3,6 @@
|
||||
Create a `Set` from `b`, then use `Array.filter()` on `a` to only keep values not contained in `b`.
|
||||
|
||||
```js
|
||||
const difference = (a, b) => { const s = new Set(b); return a.filter(x => !s.has(x)); }
|
||||
const difference = (a, b) => { const s = new Set(b); return a.filter(x => !s.has(x)); };
|
||||
// difference([1,2,3], [1,2]) -> [3]
|
||||
```
|
||||
|
||||
10
snippets/array-includes.md
Normal file
10
snippets/array-includes.md
Normal file
@ -0,0 +1,10 @@
|
||||
### Array includes
|
||||
|
||||
Use `slice()` to offset the array/string and `indexOf()` to check if the value is included.
|
||||
Omit the last argument, `fromIndex`, to check the whole array/string.
|
||||
|
||||
```js
|
||||
const includes = (collection, val, fromIndex=0) => collection.slice(fromIndex).indexOf(val) != -1;
|
||||
// includes("30-seconds-of-code", "code") -> true
|
||||
// includes([1, 2, 3, 4], [1, 2], 1) -> false
|
||||
```
|
||||
@ -3,6 +3,6 @@
|
||||
Create a `Set` from `b`, then use `Array.filter()` on `a` to only keep values contained in `b`.
|
||||
|
||||
```js
|
||||
const intersection = (a, b) => { const s = new Set(b); return a.filter(x => s.has(x)); }
|
||||
const intersection = (a, b) => { const s = new Set(b); return a.filter(x => s.has(x)); };
|
||||
// intersection([1,2,3], [4,3,2]) -> [2,3]
|
||||
```
|
||||
|
||||
9
snippets/array-sample.md
Normal file
9
snippets/array-sample.md
Normal file
@ -0,0 +1,9 @@
|
||||
### Array sample
|
||||
|
||||
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.
|
||||
|
||||
```js
|
||||
const sample = arr => arr[Math.floor(Math.random() * arr.length)];
|
||||
// sample([3, 7, 9, 11]) -> 9
|
||||
```
|
||||
@ -3,6 +3,6 @@
|
||||
Create a `Set` with all values of `a` and `b` and convert to an array.
|
||||
|
||||
```js
|
||||
const union = (a, b) => Array.from(new Set([...a, ...b]))
|
||||
const union = (a, b) => Array.from(new Set([...a, ...b]));
|
||||
// union([1,2,3], [4,3,2]) -> [1,2,3,4]
|
||||
```
|
||||
|
||||
9
snippets/array-without.md
Normal file
9
snippets/array-without.md
Normal file
@ -0,0 +1,9 @@
|
||||
### Array without
|
||||
|
||||
Use `Array.filter()` to create an array excluding all given values.
|
||||
|
||||
```js
|
||||
const without = (arr, ...args) => arr.filter(v => args.indexOf(v) === -1);
|
||||
// without[2, 1, 2, 3], 1, 2) -> [3]
|
||||
// without([2, 1, 2, 3, 4, 5, 5, 5, 3, 2, 7, 7], 3, 1, 5, 2) -> [ 4, 7, 7 ]
|
||||
```
|
||||
16
snippets/array-zip.md
Normal file
16
snippets/array-zip.md
Normal file
@ -0,0 +1,16 @@
|
||||
### Array zip
|
||||
|
||||
Use `Math.max.apply()` to get the longest array in the arguments.
|
||||
Creates an array with that length as return value and use `Array.from()` with a map-function to create an array of grouped elements.
|
||||
If lengths of the argument-arrays vary, `undefined` is used where no value could be found.
|
||||
|
||||
```js
|
||||
const zip = (...arrays) => {
|
||||
const maxLength = Math.max.apply(null, arrays.map(a => a.length));
|
||||
return Array.from({length: maxLength}).map((_, i) => {
|
||||
return Array.from({length: arrays.length}, (_, k) => arrays[k][i]);
|
||||
})
|
||||
}
|
||||
//zip(['a', 'b'], [1, 2], [true, false]); -> [['a', 1, true], ['b', 2, false]]
|
||||
//zip(['a'], [1, 2], [true, false]); -> [['a', 1, true], [undefined, 2, false]]
|
||||
```
|
||||
@ -1,10 +1,11 @@
|
||||
### Capitalize first letter
|
||||
|
||||
Use `slice(0,1)` and `toUpperCase()` to capitalize first letter, `slice(1)` to get the rest of the 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.
|
||||
|
||||
```js
|
||||
const capitalize = (str, lowerRest = false) =>
|
||||
str.slice(0, 1).toUpperCase() + (lowerRest ? str.slice(1).toLowerCase() : str.slice(1));
|
||||
const capitalize = ([first,...rest], lowerRest = false) =>
|
||||
first.toUpperCase() + (lowerRest ? rest.join('').toLowerCase() : rest.join(''));
|
||||
// capitalize('myName') -> 'MyName'
|
||||
// capitalize('myName', true) -> 'Myname'
|
||||
```
|
||||
|
||||
@ -7,5 +7,5 @@ If the original array can't be split evenly, the final chunk will contain the re
|
||||
```js
|
||||
const chunk = (arr, size) =>
|
||||
Array.from({length: Math.ceil(arr.length / size)}, (v, i) => arr.slice(i * size, i * size + size));
|
||||
// chunk([1,2,3,4,5], 2) -> [[1,2],[3,4],5]
|
||||
// chunk([1,2,3,4,5], 2) -> [[1,2],[3,4],[5]]
|
||||
```
|
||||
|
||||
9
snippets/collatz-algorithm.md
Normal file
9
snippets/collatz-algorithm.md
Normal file
@ -0,0 +1,9 @@
|
||||
### Collatz algorithm
|
||||
|
||||
If `n` is even, return `n/2`. Otherwise return `3n+1`.
|
||||
|
||||
```js
|
||||
const collatz = n => (n % 2 == 0) ? (n / 2) : (3 * n + 1);
|
||||
// collatz(8) --> 4
|
||||
// collatz(5) --> 16
|
||||
```
|
||||
@ -6,13 +6,10 @@ Otherwise return a curried function `f` that expects the rest of the arguments.
|
||||
If you want to curry a function that accepts a variable number of arguments (a variadic function, e.g. `Math.min()`), you can optionally pass the number of arguments to the second parameter `arity`.
|
||||
|
||||
```js
|
||||
const curry = (f, arity = f.length, next) =>
|
||||
(next = prevArgs =>
|
||||
nextArg => {
|
||||
const args = [ ...prevArgs, nextArg ];
|
||||
return args.length >= arity ? f(...args) : next(args);
|
||||
}
|
||||
)([]);
|
||||
const curry = (fn, arity = fn.length, ...args) =>
|
||||
arity <= args.length
|
||||
? fn(...args)
|
||||
: curry.bind(null, fn, arity, ...args);
|
||||
// curry(Math.pow)(2)(10) -> 1024
|
||||
// curry(Math.min, 3)(10)(50)(2) -> 2
|
||||
```
|
||||
|
||||
@ -1,10 +1,10 @@
|
||||
### Deep flatten array
|
||||
|
||||
Use recursion.
|
||||
Use `Array.reduce()` to get all elements that are not arrays, flatten each element that is an array.
|
||||
Use `Array.concat()` with an empty array (`[]`) and the spread operator (`...`) to flatten an array.
|
||||
Rrecursively flatten each element that is an array.
|
||||
|
||||
```js
|
||||
const deepFlatten = arr =>
|
||||
arr.reduce((a, v) => a.concat(Array.isArray(v) ? deepFlatten(v) : v), []);
|
||||
const deepFlatten = arr => [].concat(...arr.map(v => Array.isArray(v) ? deepFlatten(v) : v));
|
||||
// deepFlatten([1,[2],[[3],4],5]) -> [1,2,3,4,5]
|
||||
```
|
||||
|
||||
12
snippets/drop-elements-in-array.md
Normal file
12
snippets/drop-elements-in-array.md
Normal file
@ -0,0 +1,12 @@
|
||||
### 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`.
|
||||
Returns the remaining elements.
|
||||
|
||||
```js
|
||||
const dropElements = (arr, func) => {
|
||||
while (arr.length > 0 && !func(arr[0])) arr.shift();
|
||||
return arr;
|
||||
};
|
||||
// dropElements([1, 2, 3, 4], n => n >= 3) -> [3,4]
|
||||
```
|
||||
19
snippets/element-is-visible-in-viewport.md
Normal file
19
snippets/element-is-visible-in-viewport.md
Normal file
@ -0,0 +1,19 @@
|
||||
### Element is visible in viewport
|
||||
|
||||
Use `Element.getBoundingClientRect()` and the `window.inner(Width|Height)` values
|
||||
to determine if a given element is visible in the viewport.
|
||||
Omit the second argument to determine if the element is entirely visible, or specify `true` to determine if
|
||||
it is partially visible.
|
||||
|
||||
```js
|
||||
const elementIsVisibleInViewport = (el, partiallyVisible = false) => {
|
||||
const { top, left, bottom, right } = el.getBoundingClientRect();
|
||||
return partiallyVisible
|
||||
? ((top > 0 && top < innerHeight) || (bottom > 0 && bottom < innerHeight)) &&
|
||||
((left > 0 && left < innerWidth) || (right > 0 && right < innerWidth))
|
||||
: top >= 0 && left >= 0 && bottom <= innerHeight && right <= innerWidth;
|
||||
};
|
||||
// e.g. 100x100 viewport and a 10x10px element at position {top: -1, left: 0, bottom: 9, right: 10}
|
||||
// elementIsVisibleInViewport(el) -> false (not fully visible)
|
||||
// elementIsVisibleInViewport(el, true) -> true (partially visible)
|
||||
```
|
||||
10
snippets/fill-array.md
Normal file
10
snippets/fill-array.md
Normal file
@ -0,0 +1,10 @@
|
||||
### Fill array
|
||||
|
||||
Use `Array.map()` to map values between `start` (inclusive) and `end` (exclusive) to `value`.
|
||||
Omit `start` to start at the first element and/or `end` to finish at the last.
|
||||
|
||||
```js
|
||||
const fillArray = (arr, value, start = 0, end = arr.length) =>
|
||||
arr.map((v, i) => i >= start && i < end ? value : v);
|
||||
// fillArray([1,2,3,4],'8',1,3) -> [1,'8','8',4]
|
||||
```
|
||||
13
snippets/flatten-array-up-to-depth.md
Normal file
13
snippets/flatten-array-up-to-depth.md
Normal file
@ -0,0 +1,13 @@
|
||||
### Flatten array up to depth
|
||||
|
||||
Use recursion, decrementing `depth` by 1 for each level of depth.
|
||||
Use `Array.reduce()` and `Array.concat()` to merge elements or arrays.
|
||||
Base case, for `depth` equal to `1` stops recursion.
|
||||
Omit the second element, `depth` to flatten only to a depth of `1` (single flatten).
|
||||
|
||||
```js
|
||||
const flattenDepth = (arr, depth = 1) =>
|
||||
depth != 1 ? arr.reduce((a, v) => a.concat(Array.isArray(v) ? flattenDepth(v, depth - 1) : v), [])
|
||||
: arr.reduce((a, v) => a.concat(v), []);
|
||||
// flattenDepth([1,[2],[[[3],4],5]], 2) -> [1,2,[3],4,5]
|
||||
```
|
||||
8
snippets/get-days-difference-between-dates.md
Normal file
8
snippets/get-days-difference-between-dates.md
Normal file
@ -0,0 +1,8 @@
|
||||
### Get days difference between dates
|
||||
|
||||
Calculate the difference (in days) between to `Date` objects.
|
||||
|
||||
```js
|
||||
const getDaysDiffBetweenDates = (dateInitial, dateFinal) => (dateFinal - dateInitial) / (1000 * 3600 * 24);
|
||||
// getDaysDiffBetweenDates(new Date("2017-12-13"), new Date("2017-12-22")) -> 9
|
||||
```
|
||||
@ -5,10 +5,8 @@ Use `Array.reduce()` to create an object, where the keys are produced from the m
|
||||
|
||||
```js
|
||||
const groupBy = (arr, func) =>
|
||||
(typeof func === 'function' ? arr.map(func) : arr.map(val => val[func]))
|
||||
.reduce((acc, val, i) => {
|
||||
acc[val] = acc[val] === undefined ? [arr[i]] : acc[val].concat(arr[i]); return acc;
|
||||
}, {});
|
||||
arr.map(typeof func === 'function' ? func : val => val[func])
|
||||
.reduce((acc, val, i) => { acc[val] = (acc[val] || []).concat(arr[i]); return acc; }, {});
|
||||
// groupBy([6.1, 4.2, 6.3], Math.floor) -> {4: [4.2], 6: [6.1, 6.3]}
|
||||
// groupBy(['one', 'two', 'three'], 'length') -> {3: ['one', 'two'], 5: ['three']}
|
||||
```
|
||||
|
||||
9
snippets/is-array.md
Normal file
9
snippets/is-array.md
Normal file
@ -0,0 +1,9 @@
|
||||
### Is array
|
||||
|
||||
Use `Array.isArray()` to check if a value is classified as an array.
|
||||
|
||||
```js
|
||||
const isArray = val => !!val && Array.isArray(val);
|
||||
// isArray(null) -> false
|
||||
// isArray([1]) -> true
|
||||
```
|
||||
9
snippets/is-boolean.md
Normal file
9
snippets/is-boolean.md
Normal file
@ -0,0 +1,9 @@
|
||||
### Is boolean
|
||||
|
||||
Use `typeof` to check if a value is classified as a boolean primitive.
|
||||
|
||||
```js
|
||||
const isBoolean = val => typeof val === 'boolean';
|
||||
// isBoolean(null) -> false
|
||||
// isBoolean(false) -> true
|
||||
```
|
||||
9
snippets/is-function.md
Normal file
9
snippets/is-function.md
Normal file
@ -0,0 +1,9 @@
|
||||
### Is function
|
||||
|
||||
Use `typeof` to check if a value is classified as a function primitive.
|
||||
|
||||
```js
|
||||
const isFunction = val => val && typeof val === 'function';
|
||||
// isFunction('x') -> false
|
||||
// isFunction(x => x) -> true
|
||||
```
|
||||
9
snippets/is-number.md
Normal file
9
snippets/is-number.md
Normal file
@ -0,0 +1,9 @@
|
||||
### Is number
|
||||
|
||||
Use `typeof` to check if a value is classified as a number primitive.
|
||||
|
||||
```js
|
||||
const isNumber = val => typeof val === 'number';
|
||||
// isNumber('1') -> false
|
||||
// isNumber(1) -> true
|
||||
```
|
||||
9
snippets/is-string.md
Normal file
9
snippets/is-string.md
Normal file
@ -0,0 +1,9 @@
|
||||
### Is string
|
||||
|
||||
Use `typeof` to check if a value is classified as a string primitive.
|
||||
|
||||
```js
|
||||
const isString = val => typeof val === 'string';
|
||||
// isString(10) -> false
|
||||
// isString('10') -> true
|
||||
```
|
||||
9
snippets/is-symbol.md
Normal file
9
snippets/is-symbol.md
Normal file
@ -0,0 +1,9 @@
|
||||
### Is symbol
|
||||
|
||||
Use `typeof` to check if a value is classified as a symbol primitive.
|
||||
|
||||
```js
|
||||
const isSymbol = val => typeof val === 'symbol';
|
||||
// isSymbol('x') -> false
|
||||
// isSymbol(Symbol('x')) -> true
|
||||
```
|
||||
@ -1,13 +1,14 @@
|
||||
### Measure time taken by function
|
||||
|
||||
Use `performance.now()` to get start and end time for the function, `console.log()` the time taken.
|
||||
Pass a callback function as the argument.
|
||||
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 => {
|
||||
const t0 = performance.now(), r = callback();
|
||||
console.log(performance.now() - t0);
|
||||
console.time('timeTaken');
|
||||
const r = callback();
|
||||
console.timeEnd('timeTaken');
|
||||
return r;
|
||||
};
|
||||
// timeTaken(() => Math.pow(2, 10)) -> 1024 (0.010000000009313226 logged in console)
|
||||
// timeTaken(() => Math.pow(2, 10)) -> 1024
|
||||
// (logged): timeTaken: 0.02099609375ms
|
||||
```
|
||||
|
||||
11
snippets/nth-element-of-array.md
Normal file
11
snippets/nth-element-of-array.md
Normal file
@ -0,0 +1,11 @@
|
||||
### Nth element of array
|
||||
|
||||
Use `Array.slice()` to get an array containing the nth element at the first place.
|
||||
If the index is out of bounds, return `[]`.
|
||||
Omit the second argument, `n`, to get the first element of the array.
|
||||
|
||||
```js
|
||||
const nth = (arr, n=0) => (n>0? arr.slice(n,n+1) : arr.slice(n))[0];
|
||||
// nth(['a','b','c'],1) -> 'b'
|
||||
// nth(['a','b','b']-2) -> 'a'
|
||||
```
|
||||
9
snippets/number-to-array-of-digits.md
Normal file
9
snippets/number-to-array-of-digits.md
Normal file
@ -0,0 +1,9 @@
|
||||
### Number to array of digits
|
||||
|
||||
Convert the number to a string, use `split()` to convert build an array.
|
||||
Use `Array.map()` and `parseInt()` to transform each value to an integer.
|
||||
|
||||
```js
|
||||
const digitize = n => (''+n).split('').map(i => parseInt(i));
|
||||
// digitize(2334) -> [2, 3, 3, 4]
|
||||
```
|
||||
@ -7,9 +7,9 @@ If digit is found in teens pattern, use teens ordinal.
|
||||
```js
|
||||
const toOrdinalSuffix = num => {
|
||||
const int = parseInt(num), digits = [(int % 10), (int % 100)],
|
||||
ordinals = ["st", "nd", "rd", "th"], oPattern = [1,2,3,4],
|
||||
tPattern = [11, 12, 13, 14, 15, 16, 17, 18, 19]
|
||||
return oPattern.includes(digits[0]) && !tPattern.includes(digits[1]) ? int + ordinals[digits[0]-1] : int + ordinals[3];
|
||||
}
|
||||
ordinals = ['st', 'nd', 'rd', 'th'], oPattern = [1, 2, 3, 4],
|
||||
tPattern = [11, 12, 13, 14, 15, 16, 17, 18, 19];
|
||||
return oPattern.includes(digits[0]) && !tPattern.includes(digits[1]) ? int + ordinals[digits[0] - 1] : int + ordinals[3];
|
||||
};
|
||||
// toOrdinalSuffix("123") -> "123rd"
|
||||
```
|
||||
|
||||
@ -1,8 +1,14 @@
|
||||
### Pipe
|
||||
|
||||
Use `Array.reduce()` to pass value through functions.
|
||||
Use `Array.reduce()` to perform left-to-right function composition.
|
||||
The first (leftmost) function can accept one or more arguments; the remaining functions must be unary.
|
||||
|
||||
```js
|
||||
const pipe = (...funcs) => arg => funcs.reduce((acc, func) => func(acc), arg);
|
||||
// pipe(btoa, x => x.toUpperCase())("Test") -> "VGVZDA=="
|
||||
const pipe = (...fns) => fns.reduce((f, g) => (...args) => g(f(...args)));
|
||||
/*
|
||||
const add5 = x => x + 5
|
||||
const multiply = (x, y) => x * y
|
||||
const multiplyAndAdd5 = pipe(multiply, add5)
|
||||
multiplyAndAdd5(5, 2) -> 15
|
||||
*/
|
||||
```
|
||||
|
||||
9
snippets/round-number-to-n-digits.md
Normal file
9
snippets/round-number-to-n-digits.md
Normal file
@ -0,0 +1,9 @@
|
||||
### Round number to n 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.
|
||||
|
||||
```js
|
||||
const round = (n, decimals=0) => Number(`${Math.round(`${n}e${decimals}`)}e-${decimals}`);
|
||||
// round(1.005, 2) -> 1.01
|
||||
```
|
||||
12
snippets/shallow-clone-object.md
Normal file
12
snippets/shallow-clone-object.md
Normal file
@ -0,0 +1,12 @@
|
||||
### Shallow clone object
|
||||
|
||||
Use `Object.assign()` and an empty object (`{}`) to create a shallo clone of the original.
|
||||
|
||||
```js
|
||||
const shallowClone = obj => Object.assign({}, obj);
|
||||
/*
|
||||
const a = { x: true, y: 1 };
|
||||
const b = shallowClone(a);
|
||||
a === b -> false
|
||||
*/
|
||||
```
|
||||
15
snippets/speech-synthesis-(experimental).md
Normal file
15
snippets/speech-synthesis-(experimental).md
Normal file
@ -0,0 +1,15 @@
|
||||
### Speech synthesis (experimental)
|
||||
|
||||
Use `SpeechSynthesisUtterance.voice` and `indow.speechSynthesis.getVoices()` to convert a message to speech.
|
||||
Use `window.speechSynthesis.speak()` to play the message.
|
||||
|
||||
Learn more about the [SpeechSynthesisUtterance interface of the Web Speech API](https://developer.mozilla.org/en-US/docs/Web/API/SpeechSynthesisUtterance).
|
||||
|
||||
```js
|
||||
const speak = message => {
|
||||
const msg = new SpeechSynthesisUtterance(message);
|
||||
msg.voice = window.speechSynthesis.getVoices()[0];
|
||||
window.speechSynthesis.speak(msg);
|
||||
};
|
||||
// speak('Hello, World') -> plays the message
|
||||
```
|
||||
@ -11,7 +11,7 @@ const standardDeviation = (arr, usePopulation = false) => {
|
||||
arr.reduce((acc, val) => acc.concat(Math.pow(val - mean, 2)), [])
|
||||
.reduce((acc, val) => acc + val, 0) / (arr.length - (usePopulation ? 0 : 1))
|
||||
);
|
||||
}
|
||||
};
|
||||
// standardDeviation([10,2,38,23,38,23,21]) -> 13.284434142114991 (sample)
|
||||
// standardDeviation([10,2,38,23,38,23,21], true) -> 12.29899614287479 (population)
|
||||
```
|
||||
|
||||
9
snippets/take-right.md
Normal file
9
snippets/take-right.md
Normal file
@ -0,0 +1,9 @@
|
||||
### Take right
|
||||
|
||||
Use `Array.slice()` to create a slice of the array with `n` elements taken from the end.
|
||||
|
||||
```js
|
||||
const takeRight = (arr, n = 1) => arr.slice(arr.length - n, arr.length);
|
||||
// takeRight([1, 2, 3], 2) -> [ 2, 3 ]
|
||||
// takeRight([1, 2, 3]) -> [3]
|
||||
```
|
||||
@ -4,7 +4,6 @@ Use `Array.slice()` to create a slice of the array with `n` elements taken from
|
||||
|
||||
```js
|
||||
const take = (arr, n = 1) => arr.slice(0, n);
|
||||
|
||||
// take([1, 2, 3], 5) -> [1, 2, 3]
|
||||
// take([1, 2, 3], 0) -> []
|
||||
```
|
||||
|
||||
9
snippets/write-json-to-file.md
Normal file
9
snippets/write-json-to-file.md
Normal file
@ -0,0 +1,9 @@
|
||||
### Write a JSON 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))
|
||||
// jsonToFile({test: "is passed"}, 'testJsonFile') -> writes the object to 'testJsonFile.json'
|
||||
```
|
||||
Reference in New Issue
Block a user