diff --git a/.travis/push.sh b/.travis/push.sh
index 0cd1495b3..38e97512b 100755
--- a/.travis/push.sh
+++ b/.travis/push.sh
@@ -11,6 +11,8 @@ commit_website_files() {
git add *
if [ $TRAVIS_EVENT_TYPE == "cron" ]; then
git commit --message "Travis build: $TRAVIS_BUILD_NUMBER [cron]"
+ elif [ $TRAVIS_EVENT_TYPE == "api" ]; then
+ git commit --message "Travis build: $TRAVIS_BUILD_NUMBER [custom]"
else
git commit --message "Travis build: $TRAVIS_BUILD_NUMBER"
fi
diff --git a/README.md b/README.md
index 831b363dd..03cce1434 100644
--- a/README.md
+++ b/README.md
@@ -1,19 +1,19 @@
-
-
-# 30 seconds of code
-[](https://github.com/Chalarangelo/30-seconds-of-code/blob/master/LICENSE) [](https://gitter.im/30-seconds-of-code/Lobby) [](http://makeapullrequest.com) [](https://travis-ci.org/Chalarangelo/30-seconds-of-code) [](https://insight.io/github.com/Chalarangelo/30-seconds-of-code/tree/master/?source=0) [](https://github.com/Flet/semistandard)
-
-> Curated collection of useful Javascript snippets that you can understand in 30 seconds or less.
-
-
-- Use Ctrl + F or command + F to search for a snippet.
-- 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.
-- You can import these snippets into your text editor of choice (VSCode, Atom, Sublime) using the files found in [this repo](https://github.com/Rob-Rychs/30-seconds-of-code-texteditorsnippets).
-- You can import these snippets into Alfred 3, using [this file](https://github.com/lslvxy/30-seconds-of-code-alfredsnippets).
-- You can find a package with all the snippets on [npm](https://www.npmjs.com/package/tsoc). Bear in mind that most of these snippets are not production-ready.
-
-## Table of Contents
+
+
+# 30 seconds of code
+[](https://github.com/Chalarangelo/30-seconds-of-code/blob/master/LICENSE) [](https://gitter.im/30-seconds-of-code/Lobby) [](http://makeapullrequest.com) [](https://travis-ci.org/Chalarangelo/30-seconds-of-code) [](https://insight.io/github.com/Chalarangelo/30-seconds-of-code/tree/master/?source=0) [](https://github.com/Flet/semistandard)
+
+> Curated collection of useful Javascript snippets that you can understand in 30 seconds or less.
+
+
+- Use Ctrl + F or command + F to search for a snippet.
+- 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.
+- You can import these snippets into your text editor of choice (VSCode, Atom, Sublime) using the files found in [this repo](https://github.com/Rob-Rychs/30-seconds-of-code-texteditorsnippets).
+- You can import these snippets into Alfred 3, using [this file](https://github.com/lslvxy/30-seconds-of-code-alfredsnippets).
+- You can find a package with all the snippets on [npm](https://www.npmjs.com/package/tsoc). Bear in mind that most of these snippets are not production-ready.
+
+## Table of Contents
### 🔌 Adapter
@@ -368,17 +368,17 @@ Object.assign(b, a); // == b
[⬆ Back to top](#table-of-contents)
-### pipeFunctions
-
-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.
-
+### pipeFunctions
+
+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.
+
```js
const pipeFunctions = (...fns) => fns.reduce((f, g) => (...args) => g(f(...args)));
-```
-
+```
+
Examples
@@ -387,36 +387,36 @@ const add5 = x => x + 5;
const multiply = (x, y) => x * y;
const multiplyAndAdd5 = pipeFunctions(multiply, add5);
multiplyAndAdd5(5, 2); // 15
-```
+```
[⬆ Back to top](#table-of-contents)
-### 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.
-
-*In Node 8+, you can use [`util.promisify`](https://nodejs.org/api/util.html#util_util_promisify_original)*
-
+### 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.
+
+*In Node 8+, you can use [`util.promisify`](https://nodejs.org/api/util.html#util_util_promisify_original)*
+
```js
const promisify = func => (...args) =>
new Promise((resolve, reject) =>
func(...args, (err, result) => (err ? reject(err) : resolve(result)))
);
-```
-
+```
+
Examples
```js
const delay = promisify((d, cb) => setTimeout(cb, d));
delay(2000).then(() => console.log('Hi!')); // // Promise resolves after 2s
-```
+```
Examples
```js
chunk([1, 2, 3, 4, 5], 2); // [[1,2],[3,4],[5]]
-```
+```
[⬆ Back to top](#table-of-contents)
-### compact
-
-Removes falsey values from an array.
-
-Use `Array.filter()` to filter out falsey values (`false`, `null`, `0`, `""`, `undefined`, and `NaN`).
-
+### compact
+
+Removes falsey values from an array.
+
+Use `Array.filter()` to filter out falsey values (`false`, `null`, `0`, `""`, `undefined`, and `NaN`).
+
```js
const compact = arr => arr.filter(Boolean);
-```
-
+```
+
Examples
```js
compact([0, 1, false, 2, '', 3, 'a', 'e' * 23, NaN, 's', 34]); // [ 1, 2, 3, 'a', 's', 34 ]
-```
+```
[⬆ Back to top](#table-of-contents)
-### countOccurrences
-
-Counts the occurrences of a value in an array.
-
-Use `Array.reduce()` to increment a counter each time you encounter the specific value inside the array.
-
+### countOccurrences
+
+Counts the occurrences of a value in an array.
+
+Use `Array.reduce()` to increment a counter each time you encounter the specific value inside the array.
+
```js
const countOccurrences = (arr, value) => arr.reduce((a, v) => (v === value ? a + 1 : a + 0), 0);
-```
-
+```
+
Examples
```js
countOccurrences([1, 1, 2, 1, 2, 3], 1); // 3
-```
+```
[⬆ Back to top](#table-of-contents)
-### deepFlatten
-
-Deep flattens an array.
-
-Use recursion.
-Use `Array.concat()` with an empty array (`[]`) and the spread operator (`...`) to flatten an array.
-Recursively flatten each element that is an array.
-
+### deepFlatten
+
+Deep flattens an array.
+
+Use recursion.
+Use `Array.concat()` with an empty array (`[]`) and the spread operator (`...`) to flatten an array.
+Recursively flatten each element that is an array.
+
```js
const deepFlatten = arr => [].concat(...arr.map(v => (Array.isArray(v) ? deepFlatten(v) : v)));
-```
-
+```
+
Examples
```js
deepFlatten([1, [2], [[3], 4], 5]); // [1,2,3,4,5]
-```
+```
[⬆ Back to top](#table-of-contents)
-### 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`.
-
+### 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`.
+
```js
const difference = (a, b) => {
const s = new Set(b);
return a.filter(x => !s.has(x));
};
-```
-
+```
+
Examples
```js
difference([1, 2, 3], [1, 2, 4]); // [3]
-```
+```
[⬆ Back to top](#table-of-contents)
-### differenceWith
-
-Filters out all values from an array for which the comparator function does not return `true`.
-
-Use `Array.filter()` and `Array.find()` to find the appropriate values.
-
+### differenceWith
+
+Filters out all values from an array for which the comparator function does not return `true`.
+
+Use `Array.filter()` and `Array.find()` to find the appropriate values.
+
```js
const differenceWith = (arr, val, comp) => arr.filter(a => !val.find(b => comp(a, b)));
-```
-
+```
+
Examples
```js
differenceWith([1, 1.2, 1.5, 3], [1.9, 3], (a, b) => Math.round(a) == Math.round(b)); // [1, 1.2]
-```
+```
[⬆ Back to top](#table-of-contents)
-### distinctValuesOfArray
-
-Returns all the distinct values of an array.
-
-Use ES6 `Set` and the `...rest` operator to discard all duplicated values.
-
+### distinctValuesOfArray
+
+Returns all the distinct values of an array.
+
+Use ES6 `Set` and the `...rest` operator to discard all duplicated values.
+
```js
const distinctValuesOfArray = arr => [...new Set(arr)];
-```
-
+```
+
Examples
```js
distinctValuesOfArray([1, 2, 2, 3, 4, 4, 5]); // [1,2,3,4,5]
-```
+```
[⬆ Back to top](#table-of-contents)
-### 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.slice()` to drop the first element of the array until the returned value from the function is `true`.
-Returns the remaining elements.
-
+### 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.slice()` 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 = arr.slice(1);
return arr;
};
-```
-
+```
+
Examples
```js
dropElements([1, 2, 3, 4], n => n >= 3); // [3,4]
-```
+```
[⬆ Back to top](#table-of-contents)
-### dropRight
-
-Returns a new array with `n` elements removed from the right.
-
-Use `Array.slice()` to slice the remove the specified number of elements from the right.
-
+### dropRight
+
+Returns a new array with `n` elements removed from the right.
+
+Use `Array.slice()` to slice the remove the specified number of elements from the right.
+
```js
const dropRight = (arr, n = 1) => arr.slice(0, -n);
-```
-
+```
+
Examples
@@ -656,448 +656,448 @@ const dropRight = (arr, n = 1) => arr.slice(0, -n);
dropRight([1, 2, 3]); // [1,2]
dropRight([1, 2, 3], 2); // [1]
dropRight([1, 2, 3], 42); // []
-```
+```
[⬆ Back to top](#table-of-contents)
-### 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.
-
+### 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.
+
```js
const everyNth = (arr, nth) => arr.filter((e, i) => i % nth === nth - 1);
-```
-
+```
+
Examples
```js
everyNth([1, 2, 3, 4, 5, 6], 2); // [ 2, 4, 6 ]
-```
+```
[⬆ Back to top](#table-of-contents)
-### filterNonUnique
-
-Filters out the non-unique values in an array.
-
-Use `Array.filter()` for an array containing only the unique values.
-
+### filterNonUnique
+
+Filters out the non-unique values in an array.
+
+Use `Array.filter()` for an array containing only the unique values.
+
```js
const filterNonUnique = arr => arr.filter(i => arr.indexOf(i) === arr.lastIndexOf(i));
-```
-
+```
+
Examples
```js
filterNonUnique([1, 2, 2, 3, 4, 4, 5]); // [1,3,5]
-```
+```
[⬆ Back to top](#table-of-contents)
-### flatten
-
-Flattens an array.
-
-Use a new array and concatenate it with the spread input array causing a shallow denesting of any contained arrays.
-
+### flatten
+
+Flattens an array.
+
+Use a new array and concatenate it with the spread input array causing a shallow denesting of any contained arrays.
+
```js
const flatten = arr => [].concat(...arr);
-```
-
+```
+
Examples
```js
flatten([1, [2], 3, 4]); // [1,2,3,4]
-```
+```
[⬆ Back to top](#table-of-contents)
-### 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.
-Base case, for `depth` equal to `1` stops recursion.
-Omit the second element, `depth` to flatten only to a depth of `1` (single flatten).
-
+### 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.
+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), []);
-```
-
+```
+
Examples
```js
flattenDepth([1, [2], 3, 4]); // [1,2,3,4]
-```
+```
[⬆ Back to top](#table-of-contents)
-### groupBy
-
-Groups the elements 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.
-
+### groupBy
+
+Groups the elements 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.
+
```js
const groupBy = (arr, func) =>
arr.map(typeof func === 'function' ? func : val => val[func]).reduce((acc, val, i) => {
acc[val] = (acc[val] || []).concat(arr[i]);
return acc;
}, {});
-```
-
+```
+
Examples
```js
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']}
-```
+```
[⬆ Back to top](#table-of-contents)
-### head
-
-Returns the head of a list.
-
-Use `arr[0]` to return the first element of the passed array.
-
+### head
+
+Returns the head of a list.
+
+Use `arr[0]` to return the first element of the passed array.
+
```js
const head = arr => arr[0];
-```
-
+```
+
Examples
```js
head([1, 2, 3]); // 1
-```
+```
[⬆ Back to top](#table-of-contents)
-### 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.
-
+### 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.
+
```js
const initial = arr => arr.slice(0, -1);
-```
-
+```
+
Examples
```js
initial([1, 2, 3]); // [1,2]
-```
+```
[⬆ Back to top](#table-of-contents)
-### initialize2DArray
-
-Initializes a 2D array of given width and height and value.
-
-Use `Array.map()` to generate h rows where each is a new array of size w initialize with value. If the value is not provided, default to `null`.
-
+### initialize2DArray
+
+Initializes a 2D array of given width and height and value.
+
+Use `Array.map()` to generate h rows where each is a new array of size w initialize with value. If the value is not provided, default to `null`.
+
```js
const initialize2DArray = (w, h, val = null) =>
Array(h)
.fill()
.map(() => Array(w).fill(val));
-```
-
+```
+
Examples
```js
initialize2DArray(2, 2, 0); // [[0,0], [0,0]]
-```
+```
[⬆ Back to top](#table-of-contents)
-### initializeArrayWithRange
-
-Initializes an array containing the numbers in the specified range where `start` and `end` are inclusive.
-
-Use `Array((end + 1) - 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`.
-
+### initializeArrayWithRange
+
+Initializes an array containing the numbers in the specified range where `start` and `end` are inclusive.
+
+Use `Array((end + 1) - 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 initializeArrayWithRange = (end, start = 0) =>
Array.from({ length: end + 1 - start }).map((v, i) => i + start);
-```
-
+```
+
Examples
```js
initializeArrayWithRange(5); // [0,1,2,3,4,5]
initializeArrayWithRange(7, 3); // [3,4,5,6,7]
-```
+```
[⬆ Back to top](#table-of-contents)
-### 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`.
-
+### 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 initializeArrayWithValues = (n, value = 0) => Array(n).fill(value);
-```
-
+```
+
Examples
```js
initializeArrayWithValues(5, 2); // [2,2,2,2,2]
-```
+```
[⬆ Back to top](#table-of-contents)
-### 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`.
-
+### 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`.
+
```js
const intersection = (a, b) => {
const s = new Set(b);
return a.filter(x => s.has(x));
};
-```
-
+```
+
Examples
```js
intersection([1, 2, 3], [4, 3, 2]); // [2,3]
-```
+```
[⬆ Back to top](#table-of-contents)
-### isSorted
-
-Returns `1` if the array is sorted in ascending order, `-1` if it is sorted in descending order or `0` if it is not sorted.
-
-Calculate the ordering `direction` for the first two elements.
-Use `Object.entries()` to loop over array objects and compare them in pairs.
-Return `0` if the `direction` changes or the `direction` if the last element is reached.
-
+### isSorted
+
+Returns `1` if the array is sorted in ascending order, `-1` if it is sorted in descending order or `0` if it is not sorted.
+
+Calculate the ordering `direction` for the first two elements.
+Use `Object.entries()` to loop over array objects and compare them in pairs.
+Return `0` if the `direction` changes or the `direction` if the last element is reached.
+
```js
-const isSorted = arr => {
- const direction = arr[0] > arr[1] ? -1 : 1;
- for (let [i, val] of arr.entries())
- if (i === arr.length - 1) return direction;
- else if ((val - arr[i + 1]) * direction > 0) return 0;
-};
-```
-
+const isSorted = arr => {
+ const direction = arr[0] > arr[1] ? -1 : 1;
+ for (let [i, val] of arr.entries())
+ if (i === arr.length - 1) return direction;
+ else if ((val - arr[i + 1]) * direction > 0) return 0;
+};
+```
+
Examples
```js
-isSorted([0, 1, 2, 3]); // 1
-isSorted([0, 1, 2, 2]); // 1
-isSorted([4, 3, 2]); // -1
-isSorted([4, 3, 5]); // 0
-```
+isSorted([0, 1, 2, 3]); // 1
+isSorted([0, 1, 2, 2]); // 1
+isSorted([4, 3, 2]); // -1
+isSorted([4, 3, 5]); // 0
+```
[⬆ Back to top](#table-of-contents)
-### join
-
-Joins all elements of an array into a string and returns this string. Uses a separator and an end separator.
-
-Use `Array.reduce()` to combine elements into a string.
-Omit the second argument, `separator`, to use a default separator of `','`.
-Omit the third argument, `end`, to use the same value as `separator` by default.
-
+### join
+
+Joins all elements of an array into a string and returns this string. Uses a separator and an end separator.
+
+Use `Array.reduce()` to combine elements into a string.
+Omit the second argument, `separator`, to use a default separator of `','`.
+Omit the third argument, `end`, to use the same value as `separator` by default.
+
```js
-const join = (arr, separator = ',', end = separator) =>
- arr.reduce(
- (acc, val, i) =>
- i == arr.length - 2
- ? acc + val + end
- : i == arr.length - 1 ? acc + val : acc + val + separator,
- ''
- );
-```
-
+const join = (arr, separator = ',', end = separator) =>
+ arr.reduce(
+ (acc, val, i) =>
+ i == arr.length - 2
+ ? acc + val + end
+ : i == arr.length - 1 ? acc + val : acc + val + separator,
+ ''
+ );
+```
+
Examples
```js
-join(); // ''
-join(['pen', 'pineapple', 'apple', 'pen'], ',', '&'); //"pen,pineapple,apple&pen"
-join(['pen', 'pineapple', 'apple', 'pen'], ','); //"pen,pineapple,apple,pen"
-join(['pen', 'pineapple', 'apple', 'pen']); //"pen,pineapple,apple,pen"
-```
+join(); // ''
+join(['pen', 'pineapple', 'apple', 'pen'], ',', '&'); //"pen,pineapple,apple&pen"
+join(['pen', 'pineapple', 'apple', 'pen'], ','); //"pen,pineapple,apple,pen"
+join(['pen', 'pineapple', 'apple', 'pen']); //"pen,pineapple,apple,pen"
+```
[⬆ Back to top](#table-of-contents)
-### last
-
-Returns the last element in an array.
-
-Use `arr.length - 1` to compute the index of the last element of the given array and returning it.
-
+### last
+
+Returns the last element in an array.
+
+Use `arr.length - 1` to compute the index of the last element of the given array and returning it.
+
```js
const last = arr => arr[arr.length - 1];
-```
-
+```
+
Examples
```js
last([1, 2, 3]); // 3
-```
+```
[⬆ Back to top](#table-of-contents)
-### mapObject
-
-Maps the values of an array to an object using a function, where the key-value pairs consist of the original value as the key and the mapped value.
-
-Use an anonymous inner function scope to declare an undefined memory space, using closures to store a return value. Use a new `Array` to store the array with a map of the function over its data set and a comma operator to return a second step, without needing to move from one context to another (due to closures and order of operations).
-
+### mapObject
+
+Maps the values of an array to an object using a function, where the key-value pairs consist of the original value as the key and the mapped value.
+
+Use an anonymous inner function scope to declare an undefined memory space, using closures to store a return value. Use a new `Array` to store the array with a map of the function over its data set and a comma operator to return a second step, without needing to move from one context to another (due to closures and order of operations).
+
```js
const mapObject = (arr, fn) =>
(a => (
(a = [arr, arr.map(fn)]), a[0].reduce((acc, val, ind) => ((acc[val] = a[1][ind]), acc), {})
))();
-```
-
+```
+
Examples
```js
const squareIt = arr => mapObject(arr, a => a * a);
squareIt([1, 2, 3]); // { 1: 1, 2: 4, 3: 9 }
-```
+```
[⬆ Back to top](#table-of-contents)
-### 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 `[]`.
-Omit the second argument, `n`, to get the first element of the 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 `[]`.
+Omit the second argument, `n`, to get the first element of the array.
+
```js
const nthElement = (arr, n = 0) => (n > 0 ? arr.slice(n, n + 1) : arr.slice(n))[0];
-```
-
+```
+
Examples
```js
nthElement(['a', 'b', 'c'], 1); // 'b'
nthElement(['a', 'b', 'b'], -3); // 'a'
-```
+```
[⬆ Back to top](#table-of-contents)
-### pick
-
-Picks the key-value pairs corresponding to the given keys from an object.
-
-Use `Array.reduce()` to convert the filtered/picked keys back to an object with the corresponding key-value pair if the key exists in the obj.
-
+### pick
+
+Picks the key-value pairs corresponding to the given keys from an object.
+
+Use `Array.reduce()` to convert the filtered/picked keys back to an object with the corresponding key-value pair if the key exists in the obj.
+
```js
const pick = (obj, arr) =>
arr.reduce((acc, curr) => (curr in obj && (acc[curr] = obj[curr]), acc), {});
-```
-
+```
+
Examples
```js
pick({ a: 1, b: '2', c: 3 }, ['a', 'c']); // { 'a': 1, 'c': 3 }
-```
+```
[⬆ Back to top](#table-of-contents)
-### 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 an array by resetting it's length to zero and `Array.push()` to re-populate it with only the pulled values.
-
-_(For a snippet that does not mutate the original array see [`without`](#without))_
-
+### 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 an array by resetting it's length to zero and `Array.push()` to re-populate it with only the pulled values.
+
+_(For a snippet that does not mutate the original array see [`without`](#without))_
+
```js
const pull = (arr, ...args) => {
let argState = Array.isArray(args[0]) ? args[0] : args;
@@ -1105,8 +1105,8 @@ const pull = (arr, ...args) => {
arr.length = 0;
pulled.forEach(v => arr.push(v));
};
-```
-
+```
+
Examples
@@ -1118,21 +1118,21 @@ console.log(myArray1); // [ 'b', 'b' ]
let myArray2 = ['a', 'b', 'c', 'a', 'b', 'c'];
pull(myArray2, ['a', 'c']);
console.log(myArray2); // [ 'b', 'b' ]
-```
+```
[⬆ Back to top](#table-of-contents)
-### pullAtIndex
-
-Mutates the original array to filter out the values at the specified indexes.
-
-Use `Array.filter()` and `Array.includes()` to pull out the values that are not needed.
-Use `Array.length = 0` to mutate the passed in an array by resetting it's length to zero and `Array.push()` to re-populate it with only the pulled values.
-Use `Array.push()` to keep track of pulled values
-
+### pullAtIndex
+
+Mutates the original array to filter out the values at the specified indexes.
+
+Use `Array.filter()` and `Array.includes()` to pull out the values that are not needed.
+Use `Array.length = 0` to mutate the passed in an array by resetting it's length to zero and `Array.push()` to re-populate it with only the pulled values.
+Use `Array.push()` to keep track of pulled values
+
```js
const pullAtIndex = (arr, pullArr) => {
let removed = [];
@@ -1143,8 +1143,8 @@ const pullAtIndex = (arr, pullArr) => {
pulled.forEach(v => arr.push(v));
return removed;
};
-```
-
+```
+
Examples
@@ -1154,21 +1154,21 @@ let pulled = pullAtIndex(myArray, [1, 3]);
console.log(myArray); // [ 'a', 'c' ]
console.log(pulled); // [ 'b', 'd' ]
-```
+```
[⬆ Back to top](#table-of-contents)
-### pullAtValue
-
-Mutates the original array to filter out the values specified. Returns the removed elements.
-
-Use `Array.filter()` and `Array.includes()` to pull out the values that are not needed.
-Use `Array.length = 0` to mutate the passed in an array by resetting it's length to zero and `Array.push()` to re-populate it with only the pulled values.
-Use `Array.push()` to keep track of pulled values
-
+### pullAtValue
+
+Mutates the original array to filter out the values specified. Returns the removed elements.
+
+Use `Array.filter()` and `Array.includes()` to pull out the values that are not needed.
+Use `Array.length = 0` to mutate the passed in an array by resetting it's length to zero and `Array.push()` to re-populate it with only the pulled values.
+Use `Array.push()` to keep track of pulled values
+
```js
const pullAtValue = (arr, pullArr) => {
let removed = [],
@@ -1178,8 +1178,8 @@ const pullAtValue = (arr, pullArr) => {
mutateTo.forEach(v => arr.push(v));
return removed;
};
-```
-
+```
+
Examples
@@ -1188,21 +1188,21 @@ let myArray = ['a', 'b', 'c', 'd'];
let pulled = pullAtValue(myArray, ['b', 'd']);
console.log(myArray); // [ 'a', 'c' ]
console.log(pulled); // [ 'b', 'd' ]
-```
+```
[⬆ Back to top](#table-of-contents)
-### quickSort
-
-QuickSort an Array (ascending sort by default).
-
-Use recursion.
-Use `Array.filter` and spread operator (`...`) to create an array that all elements with values less than the pivot come before the pivot, and all elements with values greater than the pivot come after it.
-If the parameter `desc` is truthy, return array sorts in descending order.
-
+### quickSort
+
+QuickSort an Array (ascending sort by default).
+
+Use recursion.
+Use `Array.filter` and spread operator (`...`) to create an array that all elements with values less than the pivot come before the pivot, and all elements with values greater than the pivot come after it.
+If the parameter `desc` is truthy, return array sorts in descending order.
+
```js
const quickSort = ([n, ...nums], desc) =>
isNaN(n)
@@ -1212,70 +1212,70 @@ const quickSort = ([n, ...nums], desc) =>
n,
...quickSort(nums.filter(v => (!desc ? v > n : v <= n)), desc)
];
-```
-
+```
+
Examples
```js
quickSort([4, 1, 3, 2]); // [1,2,3,4]
quickSort([4, 1, 3, 2], true); // [4,3,2,1]
-```
+```
[⬆ Back to top](#table-of-contents)
-### reducedFilter
-
-Filter an array of objects based on a condition while also filtering out unspecified keys.
-
-Use `Array.filter()` to filter the array based on the predicate `fn` so that it returns the objects for which the condition returned a truthy value.
-On the filtered array, use `Array.map()` to return the new object using `Array.reduce()` to filter out the keys which were not supplied as the `keys` argument.
-
+### reducedFilter
+
+Filter an array of objects based on a condition while also filtering out unspecified keys.
+
+Use `Array.filter()` to filter the array based on the predicate `fn` so that it returns the objects for which the condition returned a truthy value.
+On the filtered array, use `Array.map()` to return the new object using `Array.reduce()` to filter out the keys which were not supplied as the `keys` argument.
+
```js
-const reducedFilter = (data, keys, fn) =>
- data.filter(fn).map(el =>
- keys.reduce((acc, key) => {
- acc[key] = el[key];
- return acc;
- }, {})
- );
-```
-
+const reducedFilter = (data, keys, fn) =>
+ data.filter(fn).map(el =>
+ keys.reduce((acc, key) => {
+ acc[key] = el[key];
+ return acc;
+ }, {})
+ );
+```
+
Examples
```js
-const data = [
- {
- id: 1,
- name: 'john',
- age: 24
- },
- {
- id: 2,
- name: 'mike',
- age: 50
- }
-];
-
-reducedFilter(data, ['id', 'name'], item => item.age > 24); // [{ id: 2, name: 'mike'}]
-```
+const data = [
+ {
+ id: 1,
+ name: 'john',
+ age: 24
+ },
+ {
+ id: 2,
+ name: 'mike',
+ age: 50
+ }
+];
+
+reducedFilter(data, ['id', 'name'], item => item.age > 24); // [{ id: 2, name: 'mike'}]
+```
[⬆ Back to top](#table-of-contents)
-### 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`).
-
+### 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`).
+
```js
const remove = (arr, func) =>
Array.isArray(arr)
@@ -1284,305 +1284,305 @@ const remove = (arr, func) =>
return acc.concat(val);
}, [])
: [];
-```
-
+```
+
Examples
```js
remove([1, 2, 3, 4], n => n % 2 == 0); // [2, 4]
-```
+```
[⬆ Back to top](#table-of-contents)
-### sample
-
-Returns a random element from an array.
-
-Use `Math.random()` to generate a random number, multiply it by `length` and round it of to the nearest whole number using `Math.floor()`.
-This method also works with strings.
-
+### sample
+
+Returns a random element from an array.
+
+Use `Math.random()` to generate a random number, multiply it by `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)];
-```
-
+```
+
Examples
```js
sample([3, 7, 9, 11]); // 9
-```
+```
[⬆ Back to top](#table-of-contents)
-### sampleSize
-
-Gets `n` random elements at unique keys from `array` up to the size of `array`.
-
-Shuffle the array using the [Fisher-Yates algorithm](https://github.com/chalarangelo/30-seconds-of-code#shuffle).
-Use `Array.slice()` to get the first `n` elements.
-Omit the second argument, `n` to get only one element at random from the array.
-
+### sampleSize
+
+Gets `n` random elements at unique keys from `array` up to the size of `array`.
+
+Shuffle the array using the [Fisher-Yates algorithm](https://github.com/chalarangelo/30-seconds-of-code#shuffle).
+Use `Array.slice()` to get the first `n` elements.
+Omit the second argument, `n` to get only one element at random from the array.
+
```js
-const sampleSize = ([...arr], n = 1) => {
- let m = arr.length;
- while (m) {
- const i = Math.floor(Math.random() * m--);
- [arr[m], arr[i]] = [arr[i], arr[m]];
- }
- return arr.slice(0, n);
-};
-```
-
+const sampleSize = ([...arr], n = 1) => {
+ let m = arr.length;
+ while (m) {
+ const i = Math.floor(Math.random() * m--);
+ [arr[m], arr[i]] = [arr[i], arr[m]];
+ }
+ return arr.slice(0, n);
+};
+```
+
Examples
```js
-sampleSize([1, 2, 3], 2); // [3,1]
-sampleSize([1, 2, 3], 4); // [2,3,1]
-```
+sampleSize([1, 2, 3], 2); // [3,1]
+sampleSize([1, 2, 3], 4); // [2,3,1]
+```
[⬆ Back to top](#table-of-contents)
-### shuffle
-
-Randomizes the order of the values of an array, returning a new array.
-
-Uses the Fisher-Yates algorithm to reorder the elements of the array, based on the [Lodash implementation](https://github.com/lodash/lodash/blob/b2ea6b1cd251796dcb5f9700c4911a7b6223920b/shuffle.js), but as a pure function.
-
+### shuffle
+
+Randomizes the order of the values of an array, returning a new array.
+
+Uses the Fisher-Yates algorithm to reorder the elements of the array, based on the [Lodash implementation](https://github.com/lodash/lodash/blob/b2ea6b1cd251796dcb5f9700c4911a7b6223920b/shuffle.js), but as a pure function.
+
```js
-const shuffle = ([...arr]) => {
- let m = arr.length;
- while (m) {
- const i = Math.floor(Math.random() * m--);
- [arr[m], arr[i]] = [arr[i], arr[m]];
- }
- return arr;
-};
-```
-
+const shuffle = ([...arr]) => {
+ let m = arr.length;
+ while (m) {
+ const i = Math.floor(Math.random() * m--);
+ [arr[m], arr[i]] = [arr[i], arr[m]];
+ }
+ return arr;
+};
+```
+
Examples
```js
-const foo = [1, 2, 3];
-shuffle(foo); // [2,3,1]
-console.log(foo); // [1,2,3]
-```
+const foo = [1, 2, 3];
+shuffle(foo); // [2,3,1]
+console.log(foo); // [1,2,3]
+```
[⬆ Back to top](#table-of-contents)
-### 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()`.
-
+### 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()`.
+
```js
const similarity = (arr, values) => arr.filter(v => values.includes(v));
-```
-
+```
+
Examples
```js
similarity([1, 2, 3], [1, 2, 4]); // [1,2]
-```
+```
[⬆ Back to top](#table-of-contents)
-### sortedIndex
-
-Returns the lowest index at which value should be inserted into array in order to maintain its sort order.
-
-Check if the array is sorted in descending order (loosely).
-Use `Array.findIndex()` to find the appropriate index where the element should be inserted.
-
+### sortedIndex
+
+Returns the lowest index at which value should be inserted into array in order to maintain its sort order.
+
+Check if the array is sorted in descending order (loosely).
+Use `Array.findIndex()` to find the appropriate index where the element should be inserted.
+
```js
-const sortedIndex = (arr, n) => {
- const isDescending = arr[0] > arr[arr.length - 1];
- const index = arr.findIndex(el => (isDescending ? n >= el : n <= el));
- return index === -1 ? arr.length : index;
-};
-```
-
+const sortedIndex = (arr, n) => {
+ const isDescending = arr[0] > arr[arr.length - 1];
+ const index = arr.findIndex(el => (isDescending ? n >= el : n <= el));
+ return index === -1 ? arr.length : index;
+};
+```
+
Examples
```js
-sortedIndex([5, 3, 2, 1], 4); // 1
-sortedIndex([30, 50], 40); // 1
-```
+sortedIndex([5, 3, 2, 1], 4); // 1
+sortedIndex([30, 50], 40); // 1
+```
[⬆ Back to top](#table-of-contents)
-### 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.
-
+### 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.
+
```js
const symmetricDifference = (a, b) => {
const sA = new Set(a),
sB = new Set(b);
return [...a.filter(x => !sB.has(x)), ...b.filter(x => !sA.has(x))];
};
-```
-
+```
+
Examples
```js
symmetricDifference([1, 2, 3], [1, 2, 4]); // [3,4]
-```
+```
[⬆ Back to top](#table-of-contents)
-### 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.
-
+### 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 tail = arr => (arr.length > 1 ? arr.slice(1) : arr);
-```
-
+```
+
Examples
```js
tail([1, 2, 3]); // [2,3]
tail([1]); // [1]
-```
+```
[⬆ Back to top](#table-of-contents)
-### take
-
-Returns an array with n elements removed from the beginning.
-
-Use `Array.slice()` to create a slice of the array with `n` elements taken from the beginning.
-
+### take
+
+Returns an array with n elements removed from the beginning.
+
+Use `Array.slice()` to create a slice of the array with `n` elements taken from the beginning.
+
```js
const take = (arr, n = 1) => arr.slice(0, n);
-```
-
+```
+
Examples
```js
take([1, 2, 3], 5); // [1, 2, 3]
take([1, 2, 3], 0); // []
-```
+```
[⬆ Back to top](#table-of-contents)
-### 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.
-
+### 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.
+
```js
const takeRight = (arr, n = 1) => arr.slice(arr.length - n, arr.length);
-```
-
+```
+
Examples
```js
takeRight([1, 2, 3], 2); // [ 2, 3 ]
takeRight([1, 2, 3]); // [3]
-```
+```
[⬆ Back to top](#table-of-contents)
-### union
-
-Returns every element that exists in any of the two arrays once.
-
-Create a `Set` with all values of `a` and `b` and convert to an array.
-
+### union
+
+Returns every element that exists in any of the two arrays once.
+
+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]));
-```
-
+```
+
Examples
```js
union([1, 2, 3], [4, 3, 2]); // [1,2,3,4]
-```
+```
[⬆ Back to top](#table-of-contents)
-### without
-
-Filters out the elements of an array, that have one of the specified values.
-
-Use `Array.filter()` to create an array excluding(using `!Array.includes()`) all given values.
-
-_(For a snippet that mutates the original array see [`pull`](#pull))_
-
+### without
+
+Filters out the elements of an array, that have one of the specified values.
+
+Use `Array.filter()` to create an array excluding(using `!Array.includes()`) all given values.
+
+_(For a snippet that mutates the original array see [`pull`](#pull))_
+
```js
const without = (arr, ...args) => arr.filter(v => !args.includes(v));
-```
-
+```
+
Examples
```js
without([2, 1, 2, 3], 1, 2); // [3]
-```
+```
[⬆ Back to top](#table-of-contents)
-### zip
-
-Creates an array of elements, grouped based on the position in the original arrays.
-
-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.
-
+### zip
+
+Creates an array of elements, grouped based on the position in the original arrays.
+
+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(...arrays.map(x => x.length));
@@ -1590,39 +1590,39 @@ const zip = (...arrays) => {
return Array.from({ length: arrays.length }, (_, k) => arrays[k][i]);
});
};
-```
-
+```
+
Examples
```js
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]]
-```
+```
[⬆ Back to top](#table-of-contents)
-### zipObject
-
-Given an array of valid property identifiers and an array of values, return an object associating the properties to the values.
-
-Since an object can have undefined values but not undefined property pointers, the array of properties is used to decide the structure of the resulting object using `Array.reduce()`.
-
+### zipObject
+
+Given an array of valid property identifiers and an array of values, return an object associating the properties to the values.
+
+Since an object can have undefined values but not undefined property pointers, the array of properties is used to decide the structure of the resulting object using `Array.reduce()`.
+
```js
const zipObject = (props, values) =>
props.reduce((obj, prop, index) => ((obj[prop] = values[index]), obj), {});
-```
-
+```
+
Examples
```js
zipObject(['a', 'b', 'c'], [1, 2]); // {a: 1, b: 2, c: undefined}
zipObject(['a', 'b'], [1, 2, 3]); // {a: 1, b: 2}
-```
+```