Update snippet descriptions

This commit is contained in:
Isabelle Viktoria Maciohsek
2020-10-22 20:24:44 +03:00
parent 5cb69e3c5c
commit aa425812b4
40 changed files with 151 additions and 87 deletions

View File

@ -5,7 +5,8 @@ tags: string,regexp,advanced
Joins all given URL segments together, then normalizes the resulting URL.
- Use `String.prototype.join('/')` to combine URL segments, then a series of `String.prototype.replace()` calls with various regexps to normalize the resulting URL (remove double slashes, add proper slashes for protocol, remove slashes before parameters, combine parameters with `'&'` and normalize first parameter delimiter).
- Use `String.prototype.join('/')` to combine URL segments.
- Use a series of `String.prototype.replace()` calls with various regexps to normalize the resulting URL (remove double slashes, add proper slashes for protocol, remove slashes before parameters, combine parameters with `'&'` and normalize first parameter delimiter).
```js
const URLJoin = (...args) =>
@ -20,5 +21,6 @@ const URLJoin = (...args) =>
```
```js
URLJoin('http://www.google.com', 'a', '/b/cd', '?foo=123', '?bar=foo'); // 'http://www.google.com/a/b/cd?foo=123&bar=foo'
URLJoin('http://www.google.com', 'a', '/b/cd', '?foo=123', '?bar=foo');
// 'http://www.google.com/a/b/cd?foo=123&bar=foo'
```

View File

@ -5,12 +5,16 @@ tags: browser,random,intermediate
Generates a UUID in a browser.
- Use `crypto` API to generate a UUID, compliant with [RFC4122](https://www.ietf.org/rfc/rfc4122.txt) version 4.
- Use `Crypto.getRandomValues()` to generate a UUID, compliant with [RFC4122](https://www.ietf.org/rfc/rfc4122.txt) version 4.
- Use `Number.prototype.toString(16)` to convert it to a proper UUID.
```js
const UUIDGeneratorBrowser = () =>
([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>
(c ^ (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)))).toString(16)
(
c ^
(crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)))
).toString(16)
);
```

View File

@ -5,7 +5,8 @@ tags: node,random,intermediate
Generates a UUID in Node.JS.
- Use `crypto` API to generate a UUID, compliant with [RFC4122](https://www.ietf.org/rfc/rfc4122.txt) version 4.
- Use `crypto.randomBytes()` to generate a UUID, compliant with [RFC4122](https://www.ietf.org/rfc/rfc4122.txt) version 4.
- Use `Number.prototype.toString(16)` to convert it to a proper UUID.
```js
const crypto = require('crypto');

View File

@ -13,5 +13,5 @@ const toRGBArray = rgbStr => rgbStr.match(/\d+/g).map(Number);
```
```js
toRGBArray('rgb(255,12,0)'); // [255, 12, 0]
toRGBArray('rgb(255, 12, 0)'); // [255, 12, 0]
```

View File

@ -17,5 +17,5 @@ const toRGBObject = rgbStr => {
```
```js
toRGBObject('rgb(255,12,0)'); // {red: 255, green: 12, blue: 0}
toRGBObject('rgb(255, 12, 0)'); // {red: 255, green: 12, blue: 0}
```

View File

@ -7,7 +7,8 @@ Converts an integer to its roman numeral representation.
Accepts value between `1` and `3999` (both inclusive).
- Create a lookup table containing 2-value arrays in the form of (roman value, integer).
- Use `Array.prototype.reduce()` to loop over the values in `lookup` and repeatedly divide `num` by the value, using `String.prototype.repeat()` to add the roman numeral representation to the accumulator.
- Use `Array.prototype.reduce()` to loop over the values in `lookup` and repeatedly divide `num` by the value.
- Use `String.prototype.repeat()` to add the roman numeral representation to the accumulator.
```js
const toRomanNumeral = num => {
@ -32,7 +33,6 @@ const toRomanNumeral = num => {
return acc;
}, '');
};
```
```js

View File

@ -10,7 +10,9 @@ Converts a value to a safe integer.
```js
const toSafeInteger = num =>
Math.round(Math.max(Math.min(num, Number.MAX_SAFE_INTEGER), Number.MIN_SAFE_INTEGER));
Math.round(
Math.max(Math.min(num, Number.MAX_SAFE_INTEGER), Number.MIN_SAFE_INTEGER)
);
```
```js

View File

@ -5,7 +5,8 @@ tags: string,regexp,intermediate
Converts a string to snake case.
- Break the string into words and combine them adding `_` as a separator, using a regexp.
- Use `String.prototype.match()` to break the string into words using an appropriate regexp.
- Use `Array.prototype.map()`, `Array.prototype.slice()`, `Array.prototype.join()` and `String.prototype.toLowerCase()` to combine them, adding `_` as a separator.
```js
const toSnakeCase = str =>
@ -19,8 +20,9 @@ const toSnakeCase = str =>
```js
toSnakeCase('camelCase'); // 'camel_case'
toSnakeCase('some text'); // 'some_text'
toSnakeCase('some-mixed_string With spaces_underscores-and-hyphens'); // 'some_mixed_string_with_spaces_underscores_and_hyphens'
toSnakeCase('some-mixed_string With spaces_underscores-and-hyphens');
// 'some_mixed_string_with_spaces_underscores_and_hyphens'
toSnakeCase('AllThe-small Things'); // 'all_the_small_things'
toSnakeCase('IAmListeningToFMWhileLoadingDifferentURLOnMyBrowserAndAlsoEditingSomeXMLAndHTML'); //
'i_am_listening_to_fm_while_loading_different_url_on_my_browser_and_also_editing_some_xml_and_html'
toKebabCase('IAmEditingSomeXMLAndHTML');
// 'i_am_editing_some_xml_and_html'
```

View File

@ -5,7 +5,8 @@ tags: string,regexp,intermediate
Converts a string to title case.
- Break the string into words, using a regexp, and combine them capitalizing the first letter of each word and adding a whitespace between them.
- Use `String.prototype.match()` to break the string into words using an appropriate regexp.
- Use `Array.prototype.map()`, `Array.prototype.slice()`, `Array.prototype.join()` and `String.prototype.toUpperCase()` to combine them, capitalizing the first letter of each word and adding a whitespace between them.
```js
const toTitleCase = str =>
@ -17,7 +18,9 @@ const toTitleCase = str =>
```js
toTitleCase('some_database_field_name'); // 'Some Database Field Name'
toTitleCase('Some label that needs to be title-cased'); // 'Some Label That Needs To Be Title Cased'
toTitleCase('Some label that needs to be title-cased');
// 'Some Label That Needs To Be Title Cased'
toTitleCase('some-package-name'); // 'Some Package Name'
toTitleCase('some-mixed_string with spaces_underscores-and-hyphens'); // 'Some Mixed String With Spaces Underscores And Hyphens'
toTitleCase('some-mixed_string with spaces_underscores-and-hyphens');
// 'Some Mixed String With Spaces Underscores And Hyphens'
```

View File

@ -5,10 +5,12 @@ tags: object,intermediate
Applies a function against an accumulator and each key in the object (from left to right).
- Use `Object.keys(obj)` to iterate over each key in the object, `Array.prototype.reduce()` to call the apply the specified function against the given accumulator.
- Use `Object.keys()` to iterate over each key in the object.
- Use `Array.prototype.reduce()` to apply the specified function against the given accumulator.
```js
const transform = (obj, fn, acc) => Object.keys(obj).reduce((a, k) => fn(a, obj[k], k, obj), acc);
const transform = (obj, fn, acc) =>
Object.keys(obj).reduce((a, k) => fn(a, obj[k], k, obj), acc);
```
```js

View File

@ -6,7 +6,7 @@ tags: browser,event,intermediate
Triggers a specific event on a given element, optionally passing custom data.
- Use `new CustomEvent()` to create an event from the specified `eventType` and details.
- Use `el.dispatchEvent()` to trigger the newly created event on the given element.
- Use `EventTarget.dispatchEvent()` to trigger the newly created event on the given element.
- Omit the third argument, `detail`, if you do not want to pass custom data to the triggered event.
```js

View File

@ -3,14 +3,21 @@ title: truthCheckCollection
tags: object,logic,array,intermediate
---
Checks if the predicate (second argument) is truthy on all elements of a collection (first argument).
Checks if the predicate function is truthy for all elements of a collection.
- Use `Array.prototype.every()` to check if each passed object has the specified property and if it returns a truthy value.
```js
const truthCheckCollection = (collection, pre) => collection.every(obj => obj[pre]);
const truthCheckCollection = (collection, pre) =>
collection.every(obj => obj[pre]);
```
```js
truthCheckCollection([{ user: 'Tinky-Winky', sex: 'male' }, { user: 'Dipsy', sex: 'male' }], 'sex'); // true
truthCheckCollection(
[
{ user: 'Tinky-Winky', sex: 'male' },
{ user: 'Dipsy', sex: 'male' },
],
'sex'
); // true
```

View File

@ -5,7 +5,7 @@ tags: function,beginner
Creates a function that accepts up to one argument, ignoring any additional arguments.
- Call the provided function, `fn`, with just the first argument given.
- Call the provided function, `fn`, with just the first argument supplied.
```js
const unary = fn => val => fn(val);

View File

@ -1,6 +1,6 @@
---
title: uncurry
tags: function,intermediate
tags: function,advanced
---
Uncurries a function up to depth `n`.

View File

@ -1,11 +1,12 @@
---
title: unescapeHTML
tags: string,browser,beginner
tags: string,browser,regexp,beginner
---
Unescapes escaped HTML characters.
- Use `String.prototype.replace()` with a regex that matches the characters that need to be unescaped, using a callback function to replace each escaped character instance with its associated unescaped character using a dictionary (object).
- Use `String.prototype.replace()` with a regexp that matches the characters that need to be unescaped.
- Use the function's callback to replace each escaped character instance with its associated unescaped character using a dictionary (object).
```js
const unescapeHTML = str =>
@ -23,5 +24,6 @@ const unescapeHTML = str =>
```
```js
unescapeHTML('&lt;a href=&quot;#&quot;&gt;Me &amp; you&lt;/a&gt;'); // '<a href="#">Me & you</a>'
```
unescapeHTML('&lt;a href=&quot;#&quot;&gt;Me &amp; you&lt;/a&gt;');
// '<a href="#">Me & you</a>'
```

View File

@ -30,5 +30,5 @@ const unflattenObject = obj =>
```js
unflattenObject({ 'a.b.c': 1, d: 1 }); // { a: { b: { c: 1 } }, d: 1 }
unflattenObject({ 'a.b': 1, 'a.c': 2, d: 3 }); // { a: { b: 1, c: 2 }, d: 3 }
unflattenObject({ 'a.b.0': 8, d: 3 }) //{ a: { b: [ 8 ] }, d: 3 }
unflattenObject({ 'a.b.0': 8, d: 3 }); // { a: { b: [ 8 ] }, d: 3 }
```

View File

@ -1,11 +1,11 @@
---
title: union
tags: array,math,beginner
tags: array,beginner
---
Returns every element that exists in any of the two arrays once.
Returns every element that exists in any of the two arrays at least once.
- Create a `Set` with all values of `a` and `b` and convert to an array.
- Create a `new Set()` with all values of `a` and `b` and convert it to an array.
```js
const union = (a, b) => Array.from(new Set([...a, ...b]));

View File

@ -3,10 +3,10 @@ title: unionBy
tags: array,intermediate
---
Returns every element that exists in any of the two arrays once, after applying the provided function to each array element of both.
Returns every element that exists in any of the two arrays at least once, after applying the provided function to each array element of both.
- Create a `Set` by applying all `fn` to all values of `a`.
- Create a `Set` from `a` and all elements in `b` whose value, after applying `fn` does not match a value in the previously created set.
- Create a `new Set()` by applying all `fn` to all values of `a`.
- Create a `new Set()` from `a` and all elements in `b` whose value, after applying `fn` does not match a value in the previously created set.
- Return the last set converted to an array.
```js
@ -18,5 +18,6 @@ const unionBy = (a, b, fn) => {
```js
unionBy([2.1], [1.2, 2.3], Math.floor); // [2.1, 1.2]
unionBy([{ id: 1 }, { id: 2 }], [{ id: 2 }, { id: 3 }], x => x.id) // [{ id: 1 }, { id: 2 }, { id: 3 }]
unionBy([{ id: 1 }, { id: 2 }], [{ id: 2 }, { id: 3 }], x => x.id)
// [{ id: 1 }, { id: 2 }, { id: 3 }]
```

View File

@ -3,15 +3,22 @@ title: unionWith
tags: array,intermediate
---
Returns every element that exists in any of the two arrays once, using a provided comparator function.
Returns every element that exists in any of the two arrays at least once, using a provided comparator function.
- Create a `Set` with all values of `a` and values in `b` for which the comparator finds no matches in `a`, using `Array.prototype.findIndex()`.
- Create a `new Set()` with all values of `a` and values in `b` for which the comparator finds no matches in `a`, using `Array.prototype.findIndex()`.
```js
const unionWith = (a, b, comp) =>
Array.from(new Set([...a, ...b.filter(x => a.findIndex(y => comp(x, y)) === -1)]));
Array.from(
new Set([...a, ...b.filter(x => a.findIndex(y => comp(x, y)) === -1)])
);
```
```js
unionWith([1, 1.2, 1.5, 3, 0], [1.9, 3, 0, 3.9], (a, b) => Math.round(a) === Math.round(b)); // [1, 1.2, 1.5, 3, 0, 3.9]
unionWith(
[1, 1.2, 1.5, 3, 0],
[1.9, 3, 0, 3.9],
(a, b) => Math.round(a) === Math.round(b)
);
// [1, 1.2, 1.5, 3, 0, 3.9]
```

View File

@ -3,9 +3,10 @@ title: uniqueElements
tags: array,beginner
---
Returns all unique values in an array.
Finds all unique values in an array.
- Create a `Set` from the given array to discard duplicated values, then use the spread operator (`...`) to convert it back to an array.
- Create a `new Set()` from the given array to discard duplicated values.
- Use the spread operator (`...`) to convert it back to an array.
```js
const uniqueElements = arr => [...new Set(arr)];

View File

@ -3,7 +3,7 @@ title: uniqueElementsBy
tags: array,intermediate
---
Returns all unique values of an array, based on a provided comparator function.
Finds all unique values of an array, based on a provided comparator function.
- Use `Array.prototype.reduce()` and `Array.prototype.some()` for an array containing only the first unique occurrence of each value, based on the comparator function, `fn`.
- The comparator function takes two arguments: the values of the two elements being compared.

View File

@ -3,7 +3,7 @@ title: uniqueElementsByRight
tags: array,intermediate
---
Returns all unique values of an array, based on a provided comparator function, starting from the right.
Finds all unique values of an array, based on a provided comparator function, starting from the right.
- Use `Array.prototype.reduceRight()` and `Array.prototype.some()` for an array containing only the last unique occurrence of each value, based on the comparator function, `fn`.
- The comparator function takes two arguments: the values of the two elements being compared.

View File

@ -5,11 +5,15 @@ tags: array,math,intermediate
Returns the unique symmetric difference between two arrays, not containing duplicate values from either array.
- Use `Array.prototype.filter()` and `Array.prototype.includes()` on each array to remove values contained in the other, then create a `Set` from the results, removing duplicate values.
- Use `Array.prototype.filter()` and `Array.prototype.includes()` on each array to remove values contained in the other.
- Create a `new Set()` from the results, removing duplicate values.
```js
const uniqueSymmetricDifference = (a, b) => [
...new Set([...a.filter(v => !b.includes(v)), ...b.filter(v => !a.includes(v))])
...new Set([
...a.filter(v => !b.includes(v)),
...b.filter(v => !a.includes(v)),
]),
];
```

View File

@ -5,12 +5,13 @@ tags: node,string,beginner
Converts a tilde path to an absolute path.
- Use `String.prototype.replace()` with a regular expression and `OS.homedir()` to replace the `~` in the start of the path with the home directory.
- Use `String.prototype.replace()` with a regular expression and `os.homedir()` to replace the `~` in the start of the path with the home directory.
```js
const untildify = str => str.replace(/^~($|\/|\\)/, `${require('os').homedir()}$1`);
const untildify = str =>
str.replace(/^~($|\/|\\)/, `${require('os').homedir()}$1`);
```
```js
untildify('~/node'); // '/Users/aUser/node'
```
```

View File

@ -5,7 +5,7 @@ tags: array,intermediate
Creates an array of arrays, ungrouping the elements in an array produced by [zip](/js/s/zip).
- Use `Math.max.apply()` to get the longest subarray in the array, `Array.prototype.map()` to make each element an array.
- Use `Math.max()`, `Function.prototype.apply()` to get the longest subarray in the array, `Array.prototype.map()` to make each element an array.
- Use `Array.prototype.reduce()` and `Array.prototype.forEach()` to map grouped values to individual arrays.
```js

View File

@ -3,9 +3,9 @@ title: unzipWith
tags: array,advanced
---
Creates an array of elements, ungrouping the elements in an array produced by [zip](#zip) and applying the provided function.
Creates an array of elements, ungrouping the elements in an array produced by [zip](/js/s/zip) and applying the provided function.
- Use `Math.max.apply()` to get the longest subarray in the array, `Array.prototype.map()` to make each element an array.
- Use `Math.max()`, `Function.prototype.apply()` to get the longest subarray in the array, `Array.prototype.map()` to make each element an array.
- Use `Array.prototype.reduce()` and `Array.prototype.forEach()` to map grouped values to individual arrays.
- Use `Array.prototype.map()` and the spread operator (`...`) to apply `fn` to each individual group of elements.
@ -22,5 +22,12 @@ const unzipWith = (arr, fn) =>
```
```js
unzipWith([[1, 10, 100], [2, 20, 200]], (...args) => args.reduce((acc, v) => acc + v, 0)); // [3, 30, 300]
unzipWith(
[
[1, 10, 100],
[2, 20, 200],
],
(...args) => args.reduce((acc, v) => acc + v, 0)
);
// [3, 30, 300]
```

View File

@ -3,12 +3,11 @@ title: vectorAngle
tags: math,beginner
---
Returns the angle (theta) between two vectors.
Calculates the angle (theta) between two vectors.
- Use `Array.prototype.reduce()`, `Math.pow()` and `Math.sqrt()` to calculate the magnitude of each vector and the scalar product of the two vectors.
- Use `Math.acos()` to calculate the arccos and get the theta value.
```js
const vectorAngle = (x, y) => {
let mX = Math.sqrt(x.reduce((acc, n) => acc + Math.pow(n, 2), 0));

View File

@ -3,7 +3,7 @@ title: vectorDistance
tags: math,beginner
---
Returns the distance between two vectors.
Calculates the distance between two vectors.
- Use `Array.prototype.reduce()`, `Math.pow()` and `Math.sqrt()` to calculate the Euclidean distance between two vectors.

View File

@ -3,7 +3,7 @@ title: weightedAverage
tags: math,intermediate
---
Returns the weighted average of two or more numbers.
Calculates the weighted average of two or more numbers.
- Use `Array.prototype.reduce()` to create the weighted sum of the values and the sum of the weights.
- Divide them with each other to get the weighted average.

View File

@ -3,19 +3,21 @@ title: weightedSample
tags: array,random,advanced
---
Returns a random element from an array, using the provided `weights` as the probabilities for each element.
Gets a random element from an array, using the provided `weights` as the probabilities for each element.
- Use `Array.prototype.reduce()` to create an array of partial sums for each value in `weights`.
- Use `Math.random()` to generate a random number and `Array.prototype.findIndex()` to find the correct index based on the array previously produced.
- Finally, return the element of `arr` with the produced index.
```js
const weightedSample = (arr, weights) => {
let roll = Math.random();
return arr[
weights
.reduce((acc, w, i) => (i === 0 ? [w] : [...acc, acc[acc.length - 1] + w]), [])
.reduce(
(acc, w, i) => (i === 0 ? [w] : [...acc, acc[acc.length - 1] + w]),
[]
)
.findIndex((v, i, s) => roll >= (i === 0 ? 0 : s[i - 1]) && roll < v)
];
};

View File

@ -1,9 +1,9 @@
---
title: when
tags: function,intermediate
tags: function,logic,beginner
---
Tests a value, `x`, against a predicate function. If `true`, return `fn(x)`. Else, return `x`.
Returns a function that takes one argument and runs a callback if it's truthy or returns it if falsy.
- Return a function expecting a single value, `x`, that returns the appropriate value based on `pred`.

View File

@ -3,9 +3,10 @@ title: without
tags: array,beginner
---
Filters out the elements of an array, that have one of the specified values.
Filters out the elements of an array that have one of the specified values.
- Use `Array.prototype.filter()` to create an array excluding(using `!Array.includes()`) all given values.
- Use `Array.prototype.includes()` to find values to exclude.
- Use `Array.prototype.filter()` to create an array excluding them.
```js
const without = (arr, ...args) => arr.filter(v => !args.includes(v));

View File

@ -15,6 +15,15 @@ const wordWrap = (str, max, br = '\n') => str.replace(
```
```js
wordWrap('Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce tempus.', 32); // 'Lorem ipsum dolor sit amet,\nconsectetur adipiscing elit.\nFusce tempus.'
wordWrap('Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce tempus.', 32, '\r\n'); // 'Lorem ipsum dolor sit amet,\r\nconsectetur adipiscing elit.\r\nFusce tempus.'
wordWrap(
'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce tempus.',
32
);
// 'Lorem ipsum dolor sit amet,\nconsectetur adipiscing elit.\nFusce tempus.'
wordWrap(
'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce tempus.',
32,
'\r\n'
);
// 'Lorem ipsum dolor sit amet,\r\nconsectetur adipiscing elit.\r\nFusce tempus.'
```

View File

@ -5,12 +5,13 @@ tags: string,regexp,intermediate
Converts a given string into an array of words.
- Use `String.prototype.split()` with a supplied pattern (defaults to non-alpha as a regexp) to convert to an array of strings.
- Use `String.prototype.split()` with a supplied `pattern` (defaults to non-alpha as a regexp) to convert to an array of strings.
- Use `Array.prototype.filter()` to remove any empty strings.
- Omit the second argument to use the default regexp.
- Omit the second argument, `pattern`, to use the default regexp.
```js
const words = (str, pattern = /[^a-zA-Z-]+/) => str.split(pattern).filter(Boolean);
const words = (str, pattern = /[^a-zA-Z-]+/) =>
str.split(pattern).filter(Boolean);
```
```js

View File

@ -5,10 +5,11 @@ tags: array,math,intermediate
Creates a new array out of the two supplied by creating each possible pair from the arrays.
- Use `Array.prototype.reduce()`, `Array.prototype.map()` and `Array.prototype.concat()` to produce every possible pair from the elements of the two arrays and save them in an array.
- Use `Array.prototype.reduce()`, `Array.prototype.map()` and `Array.prototype.concat()` to produce every possible pair from the elements of the two arrays.
```js
const xProd = (a, b) => a.reduce((acc, x) => acc.concat(b.map(y => [x, y])), []);
const xProd = (a, b) =>
a.reduce((acc, x) => acc.concat(b.map(y => [x, y])), []);
```
```js

View File

@ -3,7 +3,7 @@ title: xor
tags: math,logic,beginner
---
Returns `true` if only one of the arguments is `true`, `false` otherwise.
Checks if only one of the arguments is `true`.
- Use the logical or (`||`), and (`&&`) and not (`!`) operators on the two given values to create the logical xor.

View File

@ -5,7 +5,8 @@ tags: date,intermediate
Results in a string representation of yesterday's date.
- Use `new Date()` to get the current date, decrement by one using `Date.prototype.getDate()` and set the value to the result using `Date.prototype.setDate()`.
- Use `new Date()` to get the current date.
- Decrement it by one using `Date.prototype.getDate()` and set the value to the result using `Date.prototype.setDate()`.
- Use `Date.prototype.toISOString()` to return a string in `yyyy-mm-dd` format.
```js

View File

@ -3,11 +3,11 @@ title: zip
tags: array,intermediate
---
Creates an array of elements, grouped based on the position in the original arrays.
Creates an array of elements, grouped based on their 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.
- Use `Math.max()`, `Function.prototype.apply()` to get the longest array in the arguments.
- Create an array with that length as return value and use `Array.from()` with a mapping 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) => {

View File

@ -3,9 +3,11 @@ title: zipObject
tags: array,object,intermediate
---
Given an array of valid property identifiers and an array of values, return an object associating the properties to the values.
Associates properties to values, given array of valid property identifiers and an array of 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.prototype.reduce()`.
- Use `Array.prototype.reduce()` to build an object from the two arrays.
- If the length of `props` is longer than `values`, remaining keys will be `undefined`.
- If the length of `values` is longer than `props`, remaining values will be ignored.
```js
const zipObject = (props, values) =>
@ -15,4 +17,4 @@ const zipObject = (props, values) =>
```js
zipObject(['a', 'b', 'c'], [1, 2]); // {a: 1, b: 2, c: undefined}
zipObject(['a', 'b'], [1, 2, 3]); // {a: 1, b: 2}
```
```

View File

@ -3,17 +3,18 @@ title: zipWith
tags: array,advanced
---
Creates an array of elements, grouped based on the position in the original arrays and using function as the last value to specify how grouped values should be combined.
Creates an array of elements, grouped based on the position in the original arrays and using a function to specify how grouped values should be combined.
- Check if the last argument provided is a function.
- Use `Math.max()` 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.
- The function is invoked with the elements of each group `(...group)`.
- Use `Array.from()` to create an array with appropriate length and a mapping function to create array of grouped elements.
- If lengths of the argument arrays vary, `undefined` is used where no value could be found.
- The function is invoked with the elements of each group.
```js
const zipWith = (...array) => {
const fn = typeof array[array.length - 1] === 'function' ? array.pop() : undefined;
const fn =
typeof array[array.length - 1] === 'function' ? array.pop() : undefined;
return Array.from({ length: Math.max(...array.map(a => a.length)) }, (_, i) =>
fn ? fn(...array.map(a => a[i])) : array.map(a => a[i])
);
@ -26,6 +27,7 @@ zipWith(
[1, 2, 3],
[10, 20],
[100, 200],
(a, b, c) => (a != null ? a : 'a') + (b != null ? b : 'b') + (c != null ? c : 'c')
(a, b, c) =>
(a != null ? a : 'a') + (b != null ? b : 'b') + (c != null ? c : 'c')
); // [111, 222, '3bc']
```