Update snippet descriptions

This commit is contained in:
Isabelle Viktoria Maciohsek
2020-10-21 21:54:53 +03:00
parent 47276ac092
commit ce48fffb4d
41 changed files with 171 additions and 110 deletions

View File

@ -3,9 +3,9 @@ title: mapKeys
tags: object,intermediate tags: object,intermediate
--- ---
Creates an object with keys generated by running the provided function for each key and the same values as the provided object. Maps the keys of an object using the provided function, generating a new object.
- Use `Object.keys(obj)` to iterate over the object's keys. - Use `Object.keys()` to iterate over the object's keys.
- Use `Array.prototype.reduce()` to create a new object with the same values and mapped keys using `fn`. - Use `Array.prototype.reduce()` to create a new object with the same values and mapped keys using `fn`.
```js ```js

View File

@ -5,7 +5,7 @@ tags: math,beginner
Maps a number from one range to another range. Maps a number from one range to another range.
- Returns `num` mapped between `outMin`-`outMax` from `inMin`-`inMax`. - Return `num` mapped between `outMin`-`outMax` from `inMin`-`inMax`.
```js ```js
const mapNumRange = (num, inMin, inMax, outMin, outMax) => const mapNumRange = (num, inMin, inMax, outMin, outMax) =>

View File

@ -3,7 +3,7 @@ title: mapObject
tags: array,object,intermediate tags: array,object,intermediate
--- ---
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 result of the function as the value. Maps the values of an array to an object using a function.
- Use `Array.prototype.reduce()` to apply `fn` to each element in `arr` and combine the results into an object. - Use `Array.prototype.reduce()` to apply `fn` to each element in `arr` and combine the results into an object.
- Use `el` as the key for each property and the result of `fn` as the value. - Use `el` as the key for each property and the result of `fn` as the value.

View File

@ -3,7 +3,7 @@ title: mapString
tags: string,intermediate tags: string,intermediate
--- ---
Creates a new string with the results of calling a provided function on every character in the calling string. Creates a new string with the results of calling a provided function on every character in the given string.
- Use `String.prototype.split('')` and `Array.prototype.map()` to call the provided function, `fn`, for each character in `str`. - Use `String.prototype.split('')` and `Array.prototype.map()` to call the provided function, `fn`, for each character in `str`.
- Use `Array.prototype.join('')` to recombine the array of characters into a string. - Use `Array.prototype.join('')` to recombine the array of characters into a string.

View File

@ -3,9 +3,9 @@ title: mapValues
tags: object,intermediate tags: object,intermediate
--- ---
Creates an object with the same keys as the provided object and values generated by running the provided function for each value. Maps the values of an object using the provided function, generating a new object with the same keys.
- Use `Object.keys(obj)` to iterate over the object's keys. - Use `Object.keys()` to iterate over the object's keys.
- Use `Array.prototype.reduce()` to create a new object with the same keys and mapped values using `fn`. - Use `Array.prototype.reduce()` to create a new object with the same keys and mapped values using `fn`.
```js ```js

View File

@ -5,12 +5,15 @@ tags: string,intermediate
Replaces all but the last `num` of characters with the specified mask character. Replaces all but the last `num` of characters with the specified mask character.
- Use `String.prototype.slice()` to grab the portion of the characters that will remain unmasked and use `String.padStart()` to fill the beginning of the string with the mask character up to the original length. - Use `String.prototype.slice()` to grab the portion of the characters that will remain unmasked.
- Omit the second argument, `num`, to keep a default of `4` characters unmasked. If `num` is negative, the unmasked characters will be at the start of the string. - Use `String.padStart()` to fill the beginning of the string with the `mask` character up to the original length.
- If `num` is negative, the unmasked characters will be at the start of the string.
- Omit the second argument, `num`, to keep a default of `4` characters unmasked.
- Omit the third argument, `mask`, to use a default character of `'*'` for the mask. - Omit the third argument, `mask`, to use a default character of `'*'` for the mask.
```js ```js
const mask = (cc, num = 4, mask = '*') => `${cc}`.slice(-num).padStart(`${cc}`.length, mask); const mask = (cc, num = 4, mask = '*') =>
`${cc}`.slice(-num).padStart(`${cc}`.length, mask);
``` ```
```js ```js

View File

@ -5,14 +5,19 @@ tags: object,intermediate
Compares two objects to determine if the first one contains equivalent property values to the second one. Compares two objects to determine if the first one contains equivalent property values to the second one.
- Use `Object.keys(source)` to get all the keys of the second object, then `Array.prototype.every()`, `Object.prototype.hasOwnProperty()` and strict comparison to determine if all keys exist in the first object and have the same values. - Use `Object.keys()` to get all the keys of the second object.
- Use `Array.prototype.every()`, `Object.prototype.hasOwnProperty()` and strict comparison to determine if all keys exist in the first object and have the same values.
```js ```js
const matches = (obj, source) => const matches = (obj, source) =>
Object.keys(source).every(key => obj.hasOwnProperty(key) && obj[key] === source[key]); Object.keys(source).every(
key => obj.hasOwnProperty(key) && obj[key] === source[key]
);
``` ```
```js ```js
matches({ age: 25, hair: 'long', beard: true }, { hair: 'long', beard: true }); // true matches({ age: 25, hair: 'long', beard: true }, { hair: 'long', beard: true });
matches({ hair: 'long', beard: true }, { age: 25, hair: 'long', beard: true }); // false // true
matches({ hair: 'long', beard: true }, { age: 25, hair: 'long', beard: true });
// false
``` ```

View File

@ -5,7 +5,8 @@ tags: object,intermediate
Compares two objects to determine if the first one contains equivalent property values to the second one, based on a provided function. Compares two objects to determine if the first one contains equivalent property values to the second one, based on a provided function.
- Use `Object.keys(source)` to get all the keys of the second object, then `Array.prototype.every()`, `Object.prototype.hasOwnProperty()` and the provided function to determine if all keys exist in the first object and have equivalent values. - Use `Object.keys()` to get all the keys of the second object.
- Use `Array.prototype.every()`, `Object.prototype.hasOwnProperty()` and the provided function to determine if all keys exist in the first object and have equivalent values.
- If no function is provided, the values will be compared using the equality operator. - If no function is provided, the values will be compared using the equality operator.
```js ```js

View File

@ -5,13 +5,15 @@ tags: math,array,beginner
Returns the maximum value of an array, after mapping each element to a value using the provided function. Returns the maximum value of an array, after mapping each element to a value using the provided function.
- Use `Array.prototype.map()` to map each element to the value returned by `fn`, `Math.max()` to get the maximum value. - Use `Array.prototype.map()` to map each element to the value returned by `fn`.
- Use `Math.max()` to get the maximum value.
```js ```js
const maxBy = (arr, fn) => Math.max(...arr.map(typeof fn === 'function' ? fn : val => val[fn])); const maxBy = (arr, fn) =>
Math.max(...arr.map(typeof fn === 'function' ? fn : val => val[fn]));
``` ```
```js ```js
maxBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], o => o.n); // 8 maxBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], x => x.n); // 8
maxBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], 'n'); // 8 maxBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], 'n'); // 8
``` ```

View File

@ -1,22 +1,23 @@
--- ---
title: maxDate title: maxDate
tags: date,math,beginner tags: date,intermediate
--- ---
Returns the maximum of the given dates. Returns the maximum of the given dates.
- Use the ES6 spread syntax with `Math.max` to find the maximum date value, `new Date()` to convert it to a `Date` object. - Use the ES6 spread syntax with `Math.max()` to find the maximum date value.
- Use `new Date()` to convert it to a `Date` object.
```js ```js
const maxDate = dates => new Date(Math.max(...dates)); const maxDate = (...dates) => new Date(Math.max(...dates));
``` ```
```js ```js
const array = [ const dates = [
new Date(2017, 4, 13), new Date(2017, 4, 13),
new Date(2018, 2, 12), new Date(2018, 2, 12),
new Date(2016, 0, 10), new Date(2016, 0, 10),
new Date(2016, 0, 9) new Date(2016, 0, 9)
]; ];
maxDate(array); // 2018-03-11T22:00:00.000Z maxDate(...dates); // 2018-03-11T22:00:00.000Z
``` ```

View File

@ -1,14 +1,14 @@
--- ---
title: maxN title: maxN
tags: array,math,beginner tags: array,math,intermediate
--- ---
Returns the `n` maximum elements from the provided array. Returns the `n` maximum elements from the provided array.
If `n` is greater than or equal to the provided array's length, then return the original array (sorted in descending order).
- Use `Array.prototype.sort()` combined with the spread operator (`...`) to create a shallow clone of the array and sort it in descending order. - Use `Array.prototype.sort()` combined with the spread operator (`...`) to create a shallow clone of the array and sort it in descending order.
- Use `Array.prototype.slice()` to get the specified number of elements. - Use `Array.prototype.slice()` to get the specified number of elements.
- Omit the second argument, `n`, to get a one-element array. - Omit the second argument, `n`, to get a one-element array.
- If `n` is greater than or equal to the provided array's length, then return the original array (sorted in descending order).
```js ```js
const maxN = (arr, n = 1) => [...arr].sort((a, b) => b - a).slice(0, n); const maxN = (arr, n = 1) => [...arr].sort((a, b) => b - a).slice(0, n);
@ -16,5 +16,5 @@ const maxN = (arr, n = 1) => [...arr].sort((a, b) => b - a).slice(0, n);
```js ```js
maxN([1, 2, 3]); // [3] maxN([1, 2, 3]); // [3]
maxN([1, 2, 3], 2); // [3,2] maxN([1, 2, 3], 2); // [3, 2]
``` ```

View File

@ -6,7 +6,7 @@ tags: math,array,intermediate
Returns the median of an array of numbers. Returns the median of an array of numbers.
- Find the middle of the array, use `Array.prototype.sort()` to sort the values. - Find the middle of the array, use `Array.prototype.sort()` to sort the values.
- Return the number at the midpoint if `length` is odd, otherwise the average of the two middle numbers. - Return the number at the midpoint if `Array.prototype.length` is odd, otherwise the average of the two middle numbers.
```js ```js
const median = arr => { const median = arr => {

View File

@ -13,8 +13,10 @@ Returns the memoized (cached) function.
```js ```js
const memoize = fn => { const memoize = fn => {
const cache = new Map(); const cache = new Map();
const cached = function(val) { const cached = function (val) {
return cache.has(val) ? cache.get(val) : cache.set(val, fn.call(this, val)) && cache.get(val); return cache.has(val)
? cache.get(val)
: cache.set(val, fn.call(this, val)) && cache.get(val);
}; };
cached.cache = cache; cached.cache = cache;
return cached; return cached;
@ -25,6 +27,6 @@ const memoize = fn => {
// See the `anagrams` snippet. // See the `anagrams` snippet.
const anagramsCached = memoize(anagrams); const anagramsCached = memoize(anagrams);
anagramsCached('javascript'); // takes a long time anagramsCached('javascript'); // takes a long time
anagramsCached('javascript'); // returns virtually instantly since it's now cached anagramsCached('javascript'); // returns virtually instantly since it's cached
console.log(anagramsCached.cache); // The cached anagrams map console.log(anagramsCached.cache); // The cached anagrams map
``` ```

View File

@ -5,15 +5,17 @@ tags: object,array,intermediate
Creates a new object from the combination of two or more objects. Creates a new object from the combination of two or more objects.
- Use `Array.prototype.reduce()` combined with `Object.keys(obj)` to iterate over all objects and keys. - Use `Array.prototype.reduce()` combined with `Object.keys()` to iterate over all objects and keys.
- Use `hasOwnProperty()` and `Array.prototype.concat()` to append values for keys existing in multiple objects. - Use `Object.prototype.hasOwnProperty()` and `Array.prototype.concat()` to append values for keys existing in multiple objects.
```js ```js
const merge = (...objs) => const merge = (...objs) =>
[...objs].reduce( [...objs].reduce(
(acc, obj) => (acc, obj) =>
Object.keys(obj).reduce((a, k) => { Object.keys(obj).reduce((a, k) => {
acc[k] = acc.hasOwnProperty(k) ? [].concat(acc[k]).concat(obj[k]) : obj[k]; acc[k] = acc.hasOwnProperty(k)
? [].concat(acc[k]).concat(obj[k])
: obj[k];
return acc; return acc;
}, {}), }, {}),
{} {}
@ -30,5 +32,6 @@ const other = {
b: [2, 3], b: [2, 3],
c: 'foo' c: 'foo'
}; };
merge(object, other); // { a: [ { x: 2 }, { y: 4 }, { z: 3 } ], b: [ 1, 2, 3 ], c: 'foo' } merge(object, other);
``` // { a: [ { x: 2 }, { y: 4 }, { z: 3 } ], b: [ 1, 2, 3 ], c: 'foo' }
```

View File

@ -5,7 +5,8 @@ tags: math,beginner
Calculates the midpoint between two pairs of (x,y) points. Calculates the midpoint between two pairs of (x,y) points.
- Destructure the array to get `x1`, `y1`, `x2` and `y2`, calculate the midpoint for each dimension by dividing the sum of the two endpoints by `2`. - Destructure the array to get `x1`, `y1`, `x2` and `y2`.
- Calculate the midpoint for each dimension by dividing the sum of the two endpoints by `2`.
```js ```js
const midpoint = ([x1, y1], [x2, y2]) => [(x1 + x2) / 2, (y1 + y2) / 2]; const midpoint = ([x1, y1], [x2, y2]) => [(x1 + x2) / 2, (y1 + y2) / 2];

View File

@ -12,5 +12,5 @@ const milesToKm = miles => miles * 1.609344;
``` ```
```js ```js
milesToKm(5); // 8.04672 milesToKm(5); // ~8.04672
``` ```

View File

@ -5,13 +5,15 @@ tags: math,array,beginner
Returns the minimum value of an array, after mapping each element to a value using the provided function. Returns the minimum value of an array, after mapping each element to a value using the provided function.
- Use `Array.prototype.map()` to map each element to the value returned by `fn`, `Math.min()` to get the minimum value. - Use `Array.prototype.map()` to map each element to the value returned by `fn`.
- Use `Math.min()` to get the minimum value.
```js ```js
const minBy = (arr, fn) => Math.min(...arr.map(typeof fn === 'function' ? fn : val => val[fn])); const minBy = (arr, fn) =>
Math.min(...arr.map(typeof fn === 'function' ? fn : val => val[fn]));
``` ```
```js ```js
minBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], o => o.n); // 2 minBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], x => x.n); // 2
minBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], 'n'); // 2 minBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], 'n'); // 2
``` ```

View File

@ -1,22 +1,23 @@
--- ---
title: minDate title: minDate
tags: date,math,beginner tags: date,intermediate
--- ---
Returns the minimum of the given dates. Returns the minimum of the given dates.
- Use the ES6 spread syntax to find the minimum date value, `new Date()` to convert it to a `Date` object. - Use the ES6 spread syntax with `Math.min()` to find the minimum date value.
- Use `new Date()` to convert it to a `Date` object.
```js ```js
const minDate = dates => new Date(Math.min(...dates)); const minDate = (...dates) => new Date(Math.min(...dates));
``` ```
```js ```js
const array = [ const dates = [
new Date(2017, 4, 13), new Date(2017, 4, 13),
new Date(2018, 2, 12), new Date(2018, 2, 12),
new Date(2016, 0, 10), new Date(2016, 0, 10),
new Date(2016, 0, 9) new Date(2016, 0, 9)
]; ];
minDate(array); // 2016-01-08T22:00:00.000Z minDate(...dates); // 2016-01-08T22:00:00.000Z
``` ```

View File

@ -1,14 +1,14 @@
--- ---
title: minN title: minN
tags: array,math,beginner tags: array,math,intermediate
--- ---
Returns the `n` minimum elements from the provided array. Returns the `n` minimum elements from the provided array.
If `n` is greater than or equal to the provided array's length, then return the original array (sorted in ascending order).
- Use `Array.prototype.sort()` combined with the spread operator (`...`) to create a shallow clone of the array and sort it in ascending order. - Use `Array.prototype.sort()` combined with the spread operator (`...`) to create a shallow clone of the array and sort it in ascending order.
- Use `Array.prototype.slice()` to get the specified number of elements. - Use `Array.prototype.slice()` to get the specified number of elements.
- Omit the second argument, `n`, to get a one-element array. - Omit the second argument, `n`, to get a one-element array.
- If `n` is greater than or equal to the provided array's length, then return the original array (sorted in ascending order).
```js ```js
const minN = (arr, n = 1) => [...arr].sort((a, b) => a - b).slice(0, n); const minN = (arr, n = 1) => [...arr].sort((a, b) => a - b).slice(0, n);
@ -16,5 +16,5 @@ const minN = (arr, n = 1) => [...arr].sort((a, b) => a - b).slice(0, n);
```js ```js
minN([1, 2, 3]); // [1] minN([1, 2, 3]); // [1]
minN([1, 2, 3], 2); // [1,2] minN([1, 2, 3], 2); // [1, 2]
``` ```

View File

@ -1,14 +1,14 @@
--- ---
title: mostPerformant title: mostPerformant
tags: function,intermediate tags: function,advanced
--- ---
Returns the index of the function in an array of functions which executed the fastest. Returns the index of the function in an array of functions which executed the fastest.
- Use `Array.prototype.map()` to generate an array where each value is the total time taken to execute the function after `iterations` times. - Use `Array.prototype.map()` to generate an array where each value is the total time taken to execute the function after `iterations` times.
-Use the difference in `performance.now()` values before and after to get the total time in milliseconds to a high degree of accuracy. - Use the difference in `performance.now()` values before and after to get the total time in milliseconds to a high degree of accuracy.
- Use `Math.min()` to find the minimum execution time, and return the index of that shortest time which corresponds to the index of the most performant function. - Use `Math.min()` to find the minimum execution time, and return the index of that shortest time which corresponds to the index of the most performant function.
- Omit the second argument, `iterations`, to use a default of 10,000 iterations. - Omit the second argument, `iterations`, to use a default of `10000` iterations.
- The more iterations, the more reliable the result but the longer it will take. - The more iterations, the more reliable the result but the longer it will take.
```js ```js
@ -29,7 +29,7 @@ mostPerformant([
[1, 2, 3, 4, 5, 6, 7, 8, 9, '10'].every(el => typeof el === 'number'); [1, 2, 3, 4, 5, 6, 7, 8, 9, '10'].every(el => typeof el === 'number');
}, },
() => { () => {
// Only needs to reach index `1` before returning false // Only needs to reach index `1` before returning `false`
[1, '2', 3, 4, 5, 6, 7, 8, 9, 10].every(el => typeof el === 'number'); [1, '2', 3, 4, 5, 6, 7, 8, 9, 10].every(el => typeof el === 'number');
} }
]); // 1 ]); // 1

View File

@ -1,13 +1,13 @@
--- ---
title: nest title: nest
tags: object,intermediate tags: object,recursion,intermediate
--- ---
Given a flat array of objects linked to one another, it will nest them recursively. Nests recursively objects linked to one another in a flat array.
Useful for nesting comments, such as the ones on reddit.com.
- Use recursion. - Use recursion.
- Use `Array.prototype.filter()` to filter the items where the `id` matches the `link`, then `Array.prototype.map()` to map each one to a new object that has a `children` property which recursively nests the items based on which ones are children of the current item. - Use `Array.prototype.filter()` to filter the items where the `id` matches the `link`.
- Use `Array.prototype.map()` to map each item to a new object that has a `children` property which recursively nests the items based on which ones are children of the current item.
- Omit the second argument, `id`, to default to `null` which indicates the object is not linked to another one (i.e. it is a top level object). - Omit the second argument, `id`, to default to `null` which indicates the object is not linked to another one (i.e. it is a top level object).
- Omit the third argument, `link`, to use `'parent_id'` as the default property which links the object to another one by its `id`. - Omit the third argument, `link`, to use `'parent_id'` as the default property which links the object to another one by its `id`.
@ -19,7 +19,6 @@ const nest = (items, id = null, link = 'parent_id') =>
``` ```
```js ```js
// One top level comment
const comments = [ const comments = [
{ id: 1, parent_id: null }, { id: 1, parent_id: null },
{ id: 2, parent_id: 1 }, { id: 2, parent_id: 1 },
@ -27,5 +26,6 @@ const comments = [
{ id: 4, parent_id: 2 }, { id: 4, parent_id: 2 },
{ id: 5, parent_id: 4 } { id: 5, parent_id: 4 }
]; ];
const nestedComments = nest(comments); // [{ id: 1, parent_id: null, children: [...] }] const nestedComments = nest(comments);
// [{ id: 1, parent_id: null, children: [...] }]
``` ```

View File

@ -5,7 +5,7 @@ tags: browser,array,beginner
Converts a `NodeList` to an array. Converts a `NodeList` to an array.
- Use spread operator inside new array to convert a `NodeList` to an array. - Use spread operator (`...`) inside new array to convert a `NodeList` to an array.
```js ```js
const nodeListToArray = nodeList => [...nodeList]; const nodeListToArray = nodeList => [...nodeList];

View File

@ -3,7 +3,7 @@ title: none
tags: array,beginner tags: array,beginner
--- ---
Returns `true` if the provided predicate function returns `false` for all elements in a collection, `false` otherwise. Checks if the provided predicate function returns `false` for all elements in a collection.
- Use `Array.prototype.some()` to test if any elements in the collection return `true` based on `fn`. - Use `Array.prototype.some()` to test if any elements in the collection return `true` based on `fn`.
- Omit the second argument, `fn`, to use `Boolean` as a default. - Omit the second argument, `fn`, to use `Boolean` as a default.

View File

@ -1,6 +1,6 @@
--- ---
title: normalizeLineEndings title: normalizeLineEndings
tags: string,intermediate tags: string,regexp,intermediate
--- ---
Normalizes line endings in a string. Normalizes line endings in a string.
@ -9,10 +9,13 @@ Normalizes line endings in a string.
- Omit the second argument, `normalized`, to use the default value of `'\r\n'`. - Omit the second argument, `normalized`, to use the default value of `'\r\n'`.
```js ```js
const normalizeLineEndings = (str, normalized = '\r\n') => str.replace(/\r?\n/g, normalized); const normalizeLineEndings = (str, normalized = '\r\n') =>
str.replace(/\r?\n/g, normalized);
``` ```
```js ```js
normalizeLineEndings('This\r\nis a\nmultiline\nstring.\r\n'); // 'This\r\nis a\r\nmultiline\r\nstring.\r\n' normalizeLineEndings('This\r\nis a\nmultiline\nstring.\r\n');
normalizeLineEndings('This\r\nis a\nmultiline\nstring.\r\n', '\n'); // 'This\nis a\nmultiline\nstring.\n' // 'This\r\nis a\r\nmultiline\r\nstring.\r\n'
normalizeLineEndings('This\r\nis a\nmultiline\nstring.\r\n', '\n');
// 'This\nis a\nmultiline\nstring.\n'
``` ```

View File

@ -3,9 +3,10 @@ title: nthArg
tags: function,beginner tags: function,beginner
--- ---
Creates a function that gets the argument at index `n`. If `n` is negative, the nth argument from the end is returned. Creates a function that gets the argument at index `n`.
- Use `Array.prototype.slice()` to get the desired argument at index `n`. - Use `Array.prototype.slice()` to get the desired argument at index `n`.
- If `n` is negative, the nth argument from the end is returned.
```js ```js
const nthArg = n => (...args) => args.slice(n)[0]; const nthArg = n => (...args) => args.slice(n)[0];

View File

@ -10,7 +10,8 @@ Returns the nth element of an array.
- Omit the second argument, `n`, to get the first element of the array. - Omit the second argument, `n`, to get the first element of the array.
```js ```js
const nthElement = (arr, n = 0) => (n === -1 ? arr.slice(n) : arr.slice(n, n + 1))[0]; const nthElement = (arr, n = 0) =>
(n === -1 ? arr.slice(n) : arr.slice(n, n + 1))[0];
``` ```
```js ```js

View File

@ -8,7 +8,8 @@ Creates an object from the given key-value pairs.
- Use `Array.prototype.reduce()` to create and combine key-value pairs. - Use `Array.prototype.reduce()` to create and combine key-value pairs.
```js ```js
const objectFromPairs = arr => arr.reduce((a, [key, val]) => ((a[key] = val), a), {}); const objectFromPairs = arr =>
arr.reduce((a, [key, val]) => ((a[key] = val), a), {});
``` ```
```js ```js

View File

@ -1,27 +1,32 @@
--- ---
title: objectToQueryString title: objectToQueryString
tags: object,intermediate tags: object,advanced
--- ---
Returns a query string generated from the key-value pairs of the given object. Returns a query string generated from the key-value pairs of the given object.
- Use `Array.prototype.reduce()` on `Object.entries(queryParameters)` to create the query string. - Use `Array.prototype.reduce()` on `Object.entries(queryParameters)` to create the query string.
- Determine the `symbol` to be either `?` or `&` based on the length of `queryString` and concatenate `val` to `queryString` only if it's a string. - Determine the `symbol` to be either `?` or `&` based on the length of `queryString`.
- Concatenate `val` to `queryString` only if it's a string.
- Return the `queryString` or an empty string when the `queryParameters` are falsy. - Return the `queryString` or an empty string when the `queryParameters` are falsy.
```js ```js
const objectToQueryString = queryParameters => { const objectToQueryString = queryParameters => {
return queryParameters return queryParameters
? Object.entries(queryParameters).reduce((queryString, [key, val], index) => { ? Object.entries(queryParameters).reduce(
const symbol = queryString.length === 0 ? '?' : '&'; (queryString, [key, val], index) => {
queryString += typeof val === 'string' ? `${symbol}${key}=${val}` : ''; const symbol = queryString.length === 0 ? '?' : '&';
return queryString; queryString +=
}, '') typeof val === 'string' ? `${symbol}${key}=${val}` : '';
return queryString;
},
''
)
: ''; : '';
}; };
``` ```
```js ```js
objectToQueryString({ page: '1', size: '2kg', key: undefined }); // '?page=1&size=2kg' objectToQueryString({ page: '1', size: '2kg', key: undefined });
// '?page=1&size=2kg'
``` ```

View File

@ -3,7 +3,7 @@ title: observeMutations
tags: browser,event,advanced tags: browser,event,advanced
--- ---
Returns a new MutationObserver and runs the provided callback for each mutation on the specified element. Returns a new `MutationObserver` and runs the provided callback for each mutation on the specified element.
- Use a [`MutationObserver`](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver) to observe mutations on the given element. - Use a [`MutationObserver`](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver) to observe mutations on the given element.
- Use `Array.prototype.forEach()` to run the callback for each mutation that is observed. - Use `Array.prototype.forEach()` to run the callback for each mutation that is observed.
@ -11,7 +11,9 @@ Returns a new MutationObserver and runs the provided callback for each mutation
```js ```js
const observeMutations = (element, callback, options) => { const observeMutations = (element, callback, options) => {
const observer = new MutationObserver(mutations => mutations.forEach(m => callback(m))); const observer = new MutationObserver(mutations =>
mutations.forEach(m => callback(m))
);
observer.observe( observer.observe(
element, element,
Object.assign( Object.assign(
@ -21,7 +23,7 @@ const observeMutations = (element, callback, options) => {
attributeOldValue: true, attributeOldValue: true,
characterData: true, characterData: true,
characterDataOldValue: true, characterDataOldValue: true,
subtree: true subtree: true,
}, },
options options
) )
@ -31,6 +33,8 @@ const observeMutations = (element, callback, options) => {
``` ```
```js ```js
const obs = observeMutations(document, console.log); // Logs all mutations that happen on the page const obs = observeMutations(document, console.log);
obs.disconnect(); // Disconnects the observer and stops logging mutations on the page // Logs all mutations that happen on the page
``` obs.disconnect();
// Disconnects the observer and stops logging mutations on the page
```

View File

@ -9,7 +9,8 @@ Removes an event listener from an element.
- Omit the fourth argument `opts` to use `false` or specify it based on the options used when the event listener was added. - Omit the fourth argument `opts` to use `false` or specify it based on the options used when the event listener was added.
```js ```js
const off = (el, evt, fn, opts = false) => el.removeEventListener(evt, fn, opts); const off = (el, evt, fn, opts = false) =>
el.removeEventListener(evt, fn, opts);
``` ```
```js ```js

View File

@ -6,7 +6,7 @@ tags: array,beginner
Moves the specified amount of elements to the end of the array. Moves the specified amount of elements to the end of the array.
- Use `Array.prototype.slice()` twice to get the elements after the specified index and the elements before that. - Use `Array.prototype.slice()` twice to get the elements after the specified index and the elements before that.
- Use the spread operator(`...`) to combine the two into one array. - Use the spread operator (`...`) to combine the two into one array.
- If `offset` is negative, the elements will be moved from end to start. - If `offset` is negative, the elements will be moved from end to start.
```js ```js

View File

@ -5,7 +5,7 @@ tags: object,intermediate
Omits the key-value pairs corresponding to the given keys from an object. Omits the key-value pairs corresponding to the given keys from an object.
- Use `Object.keys(obj)`, `Array.prototype.filter()` and `Array.prototype.includes()` to remove the provided keys. - Use `Object.keys()`, `Array.prototype.filter()` and `Array.prototype.includes()` to remove the provided keys.
- Use `Array.prototype.reduce()` to convert the filtered keys back to an object with the corresponding key-value pairs. - Use `Array.prototype.reduce()` to convert the filtered keys back to an object with the corresponding key-value pairs.
```js ```js

View File

@ -3,10 +3,11 @@ title: omitBy
tags: object,intermediate tags: object,intermediate
--- ---
Creates an object composed of the properties the given function returns falsy for. The function is invoked with two arguments: (value, key). Omits the key-value pairs corresponding to the keys of the object for which the given function returns falsy.
- Use `Object.keys(obj)` and `Array.prototype.filter()`to remove the keys for which `fn` returns a truthy value. - Use `Object.keys()` and `Array.prototype.filter()` to remove the keys for which `fn` returns a truthy value.
- Use `Array.prototype.reduce()` to convert the filtered keys back to an object with the corresponding key-value pairs. - Use `Array.prototype.reduce()` to convert the filtered keys back to an object with the corresponding key-value pairs.
- The callback function is invoked with two arguments: (value, key).
```js ```js
const omitBy = (obj, fn) => const omitBy = (obj, fn) =>

View File

@ -7,13 +7,18 @@ Adds an event listener to an element with the ability to use event delegation.
- Use `EventTarget.addEventListener()` to add an event listener to an element. - Use `EventTarget.addEventListener()` to add an event listener to an element.
- If there is a `target` property supplied to the options object, ensure the event target matches the target specified and then invoke the callback by supplying the correct `this` context. - If there is a `target` property supplied to the options object, ensure the event target matches the target specified and then invoke the callback by supplying the correct `this` context.
- Returns a reference to the custom delegator function, in order to be possible to use with [`off`](#off).
- Omit `opts` to default to non-delegation behavior and event bubbling. - Omit `opts` to default to non-delegation behavior and event bubbling.
- Returns a reference to the custom delegator function, in order to be possible to use with [`off`](/js/s/off).
```js ```js
const on = (el, evt, fn, opts = {}) => { const on = (el, evt, fn, opts = {}) => {
const delegatorFn = e => e.target.matches(opts.target) && fn.call(e.target, e); const delegatorFn = e =>
el.addEventListener(evt, opts.target ? delegatorFn : fn, opts.options || false); e.target.matches(opts.target) && fn.call(e.target, e);
el.addEventListener(
evt,
opts.target ? delegatorFn : fn,
opts.options || false
);
if (opts.target) return delegatorFn; if (opts.target) return delegatorFn;
}; };
``` ```
@ -21,6 +26,8 @@ const on = (el, evt, fn, opts = {}) => {
```js ```js
const fn = () => console.log('!'); const fn = () => console.log('!');
on(document.body, 'click', fn); // logs '!' upon clicking the body on(document.body, 'click', fn); // logs '!' upon clicking the body
on(document.body, 'click', fn, { target: 'p' }); // logs '!' upon clicking a `p` element child of the body on(document.body, 'click', fn, { target: 'p' });
on(document.body, 'click', fn, { options: true }); // use capturing instead of bubbling // logs '!' upon clicking a `p` element child of the body
on(document.body, 'click', fn, { options: true });
// use capturing instead of bubbling
``` ```

View File

@ -3,11 +3,11 @@ title: onUserInputChange
tags: browser,event,advanced tags: browser,event,advanced
--- ---
Run the callback whenever the user input type changes (`mouse` or `touch`). Useful for enabling/disabling code depending on the input device. This process is dynamic and works with hybrid devices (e.g. touchscreen laptops). Runs the callback whenever the user input type changes (`mouse` or `touch`).
- Use two event listeners. - Use two event listeners.
- Assume `mouse` input initially and bind a `touchstart` event listener to the document. - Assume `mouse` input initially and bind a `'touchstart'` event listener to the document.
- On `touchstart`, add a `mousemove` event listener to listen for two consecutive `mousemove` events firing within 20ms, using `performance.now()`. - On `'touchstart'`, add a `'mousemove'` event listener to listen for two consecutive `'mousemove'` events firing within 20ms, using `performance.now()`.
- Run the callback with the input type as an argument in either of these situations. - Run the callback with the input type as an argument in either of these situations.
```js ```js
@ -17,12 +17,16 @@ const onUserInputChange = callback => {
const mousemoveHandler = () => { const mousemoveHandler = () => {
const now = performance.now(); const now = performance.now();
if (now - lastTime < 20) if (now - lastTime < 20)
(type = 'mouse'), callback(type), document.removeEventListener('mousemove', mousemoveHandler); (type = 'mouse'),
callback(type),
document.removeEventListener('mousemove', mousemoveHandler);
lastTime = now; lastTime = now;
}; };
document.addEventListener('touchstart', () => { document.addEventListener('touchstart', () => {
if (type === 'touch') return; if (type === 'touch') return;
(type = 'touch'), callback(type), document.addEventListener('mousemove', mousemoveHandler); (type = 'touch'),
callback(type),
document.addEventListener('mousemove', mousemoveHandler);
}); });
}; };
``` ```

View File

@ -24,5 +24,6 @@ const once = fn => {
const startApp = function(event) { const startApp = function(event) {
console.log(this, event); // document.body, MouseEvent console.log(this, event); // document.body, MouseEvent
}; };
document.body.addEventListener('click', once(startApp)); // only runs `startApp` once upon click document.body.addEventListener('click', once(startApp));
// only runs `startApp` once upon click
``` ```

View File

@ -3,7 +3,7 @@ title: or
tags: math,logic,beginner tags: math,logic,beginner
--- ---
Returns `true` if at least one of the arguments is `true`, `false` otherwise. Checks if at least one of the arguments is `true`.
- Use the logical or (`||`) operator on the two given values. - Use the logical or (`||`) operator on the two given values.

View File

@ -1,19 +1,23 @@
--- ---
title: orderBy title: orderBy
tags: object,array,intermediate tags: object,array,advanced
--- ---
Returns a sorted array of objects ordered by properties and orders. Sorts an array of objects, ordered by properties and orders.
- Uses `Array.prototype.sort()`, `Array.prototype.reduce()` on the `props` array with a default value of `0`, use array destructuring to swap the properties position depending on the order passed. - Uses `Array.prototype.sort()`, `Array.prototype.reduce()` on the `props` array with a default value of `0`.
- If no `orders` array is passed it sort by `'asc'` by default. - Use array destructuring to swap the properties position depending on the order supplied.
- If no `orders` array is supplied, sort by `'asc'` by default.
```js ```js
const orderBy = (arr, props, orders) => const orderBy = (arr, props, orders) =>
[...arr].sort((a, b) => [...arr].sort((a, b) =>
props.reduce((acc, prop, i) => { props.reduce((acc, prop, i) => {
if (acc === 0) { if (acc === 0) {
const [p1, p2] = orders && orders[i] === 'desc' ? [b[prop], a[prop]] : [a[prop], b[prop]]; const [p1, p2] =
orders && orders[i] === 'desc'
? [b[prop], a[prop]]
: [a[prop], b[prop]];
acc = p1 > p2 ? 1 : p1 < p2 ? -1 : 0; acc = p1 > p2 ? 1 : p1 < p2 ? -1 : 0;
} }
return acc; return acc;
@ -22,7 +26,13 @@ const orderBy = (arr, props, orders) =>
``` ```
```js ```js
const users = [{ name: 'fred', age: 48 }, { name: 'barney', age: 36 }, { name: 'fred', age: 40 }]; const users = [
orderBy(users, ['name', 'age'], ['asc', 'desc']); // [{name: 'barney', age: 36}, {name: 'fred', age: 48}, {name: 'fred', age: 40}] { name: 'fred', age: 48 },
orderBy(users, ['name', 'age']); // [{name: 'barney', age: 36}, {name: 'fred', age: 40}, {name: 'fred', age: 48}] { name: 'barney', age: 36 },
{ name: 'fred', age: 40 },
];
orderBy(users, ['name', 'age'], ['asc', 'desc']);
// [{name: 'barney', age: 36}, {name: 'fred', age: 48}, {name: 'fred', age: 40}]
orderBy(users, ['name', 'age']);
// [{name: 'barney', age: 36}, {name: 'fred', age: 40}, {name: 'fred', age: 48}]
``` ```

View File

@ -3,7 +3,7 @@ title: orderWith
tags: array,object,intermediate tags: array,object,intermediate
--- ---
Returns a sorted array of objects ordered by a property, based on the array of orders provided. Sorts an array of objects, ordered by a property, based on the array of orders provided.
- Use `Array.prototype.reduce()` to create an object from the `order` array with the values as keys and their original index as the value. - Use `Array.prototype.reduce()` to create an object from the `order` array with the values as keys and their original index as the value.
- Use `Array.prototype.sort()` to sort the given array, skipping elements for which `prop` is empty or not in the `order` array. - Use `Array.prototype.sort()` to sort the given array, skipping elements for which `prop` is empty or not in the `order` array.

View File

@ -13,5 +13,5 @@ const over = (...fns) => (...args) => fns.map(fn => fn.apply(null, args));
```js ```js
const minMax = over(Math.min, Math.max); const minMax = over(Math.min, Math.max);
minMax(1, 2, 3, 4, 5); // [1,5] minMax(1, 2, 3, 4, 5); // [1, 5]
``` ```

View File

@ -8,7 +8,8 @@ Creates a function that invokes the provided function with its arguments transfo
- Use `Array.prototype.map()` to apply `transforms` to `args` in combination with the spread operator (`...`) to pass the transformed arguments to `fn`. - Use `Array.prototype.map()` to apply `transforms` to `args` in combination with the spread operator (`...`) to pass the transformed arguments to `fn`.
```js ```js
const overArgs = (fn, transforms) => (...args) => fn(...args.map((val, i) => transforms[i](val))); const overArgs = (fn, transforms) =>
(...args) => fn(...args.map((val, i) => transforms[i](val)));
``` ```
```js ```js