From aa425812b4528b7cc762c59e31ac7db79f199396 Mon Sep 17 00:00:00 2001 From: Isabelle Viktoria Maciohsek Date: Thu, 22 Oct 2020 20:24:44 +0300 Subject: [PATCH] Update snippet descriptions --- snippets/URLJoin.md | 6 ++++-- snippets/UUIDGeneratorBrowser.md | 8 ++++++-- snippets/UUIDGeneratorNode.md | 3 ++- snippets/toRGBArray.md | 2 +- snippets/toRGBObject.md | 2 +- snippets/toRomanNumeral.md | 4 ++-- snippets/toSafeInteger.md | 4 +++- snippets/toSnakeCase.md | 10 ++++++---- snippets/toTitleCase.md | 9 ++++++--- snippets/transform.md | 6 ++++-- snippets/triggerEvent.md | 2 +- snippets/truthCheckCollection.md | 13 ++++++++++--- snippets/unary.md | 2 +- snippets/uncurry.md | 2 +- snippets/unescapeHTML.md | 10 ++++++---- snippets/unflattenObject.md | 2 +- snippets/union.md | 6 +++--- snippets/unionBy.md | 9 +++++---- snippets/unionWith.md | 15 +++++++++++---- snippets/uniqueElements.md | 5 +++-- snippets/uniqueElementsBy.md | 2 +- snippets/uniqueElementsByRight.md | 2 +- snippets/uniqueSymmetricDifference.md | 8 ++++++-- snippets/untildify.md | 7 ++++--- snippets/unzip.md | 2 +- snippets/unzipWith.md | 13 ++++++++++--- snippets/vectorAngle.md | 3 +-- snippets/vectorDistance.md | 2 +- snippets/weightedAverage.md | 2 +- snippets/weightedSample.md | 8 +++++--- snippets/when.md | 4 ++-- snippets/without.md | 5 +++-- snippets/wordWrap.md | 13 +++++++++++-- snippets/words.md | 7 ++++--- snippets/xProd.md | 5 +++-- snippets/xor.md | 2 +- snippets/yesterday.md | 3 ++- snippets/zip.md | 8 ++++---- snippets/zipObject.md | 8 +++++--- snippets/zipWith.md | 14 ++++++++------ 40 files changed, 151 insertions(+), 87 deletions(-) diff --git a/snippets/URLJoin.md b/snippets/URLJoin.md index 245c8b097..e71e6e7c1 100644 --- a/snippets/URLJoin.md +++ b/snippets/URLJoin.md @@ -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' ``` diff --git a/snippets/UUIDGeneratorBrowser.md b/snippets/UUIDGeneratorBrowser.md index c82f24509..2f1f88d01 100644 --- a/snippets/UUIDGeneratorBrowser.md +++ b/snippets/UUIDGeneratorBrowser.md @@ -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) ); ``` diff --git a/snippets/UUIDGeneratorNode.md b/snippets/UUIDGeneratorNode.md index a35700257..83f890022 100644 --- a/snippets/UUIDGeneratorNode.md +++ b/snippets/UUIDGeneratorNode.md @@ -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'); diff --git a/snippets/toRGBArray.md b/snippets/toRGBArray.md index c69638465..de2480816 100644 --- a/snippets/toRGBArray.md +++ b/snippets/toRGBArray.md @@ -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] ``` diff --git a/snippets/toRGBObject.md b/snippets/toRGBObject.md index 4cfa951a7..7d7c6e9a2 100644 --- a/snippets/toRGBObject.md +++ b/snippets/toRGBObject.md @@ -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} ``` diff --git a/snippets/toRomanNumeral.md b/snippets/toRomanNumeral.md index 298700856..7dd652b89 100644 --- a/snippets/toRomanNumeral.md +++ b/snippets/toRomanNumeral.md @@ -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 diff --git a/snippets/toSafeInteger.md b/snippets/toSafeInteger.md index 63eb88d90..58a6c58a2 100644 --- a/snippets/toSafeInteger.md +++ b/snippets/toSafeInteger.md @@ -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 diff --git a/snippets/toSnakeCase.md b/snippets/toSnakeCase.md index 12ba7f85c..3873c543c 100644 --- a/snippets/toSnakeCase.md +++ b/snippets/toSnakeCase.md @@ -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' ``` diff --git a/snippets/toTitleCase.md b/snippets/toTitleCase.md index 9ae72c926..10b14992e 100644 --- a/snippets/toTitleCase.md +++ b/snippets/toTitleCase.md @@ -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' ``` diff --git a/snippets/transform.md b/snippets/transform.md index 41df6cf41..e3f0285c5 100644 --- a/snippets/transform.md +++ b/snippets/transform.md @@ -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 diff --git a/snippets/triggerEvent.md b/snippets/triggerEvent.md index 514b0e40d..c94c33c78 100644 --- a/snippets/triggerEvent.md +++ b/snippets/triggerEvent.md @@ -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 diff --git a/snippets/truthCheckCollection.md b/snippets/truthCheckCollection.md index 8617670db..4b313f0ef 100644 --- a/snippets/truthCheckCollection.md +++ b/snippets/truthCheckCollection.md @@ -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 ``` diff --git a/snippets/unary.md b/snippets/unary.md index 77c63ec32..5dc1496b7 100644 --- a/snippets/unary.md +++ b/snippets/unary.md @@ -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); diff --git a/snippets/uncurry.md b/snippets/uncurry.md index f6bdd292b..f32c00c0b 100644 --- a/snippets/uncurry.md +++ b/snippets/uncurry.md @@ -1,6 +1,6 @@ --- title: uncurry -tags: function,intermediate +tags: function,advanced --- Uncurries a function up to depth `n`. diff --git a/snippets/unescapeHTML.md b/snippets/unescapeHTML.md index b8683264a..780f4585a 100644 --- a/snippets/unescapeHTML.md +++ b/snippets/unescapeHTML.md @@ -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('<a href="#">Me & you</a>'); // 'Me & you' -``` \ No newline at end of file +unescapeHTML('<a href="#">Me & you</a>'); +// 'Me & you' +``` diff --git a/snippets/unflattenObject.md b/snippets/unflattenObject.md index bbe11292c..9a9cb7078 100644 --- a/snippets/unflattenObject.md +++ b/snippets/unflattenObject.md @@ -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 } ``` diff --git a/snippets/union.md b/snippets/union.md index 5ef35770f..d99f298d3 100644 --- a/snippets/union.md +++ b/snippets/union.md @@ -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])); diff --git a/snippets/unionBy.md b/snippets/unionBy.md index 91251fa7a..510e8cc86 100644 --- a/snippets/unionBy.md +++ b/snippets/unionBy.md @@ -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 }] ``` diff --git a/snippets/unionWith.md b/snippets/unionWith.md index 6c4e949fd..bcc2ee1e4 100644 --- a/snippets/unionWith.md +++ b/snippets/unionWith.md @@ -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] ``` diff --git a/snippets/uniqueElements.md b/snippets/uniqueElements.md index 27452185c..4a1e99494 100644 --- a/snippets/uniqueElements.md +++ b/snippets/uniqueElements.md @@ -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)]; diff --git a/snippets/uniqueElementsBy.md b/snippets/uniqueElementsBy.md index 026142597..bb4bcef61 100644 --- a/snippets/uniqueElementsBy.md +++ b/snippets/uniqueElementsBy.md @@ -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. diff --git a/snippets/uniqueElementsByRight.md b/snippets/uniqueElementsByRight.md index 7f1994fce..6066e0c27 100644 --- a/snippets/uniqueElementsByRight.md +++ b/snippets/uniqueElementsByRight.md @@ -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. diff --git a/snippets/uniqueSymmetricDifference.md b/snippets/uniqueSymmetricDifference.md index 8772312a3..8226e7ec9 100644 --- a/snippets/uniqueSymmetricDifference.md +++ b/snippets/uniqueSymmetricDifference.md @@ -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)), + ]), ]; ``` diff --git a/snippets/untildify.md b/snippets/untildify.md index d4017670c..394e2cf48 100644 --- a/snippets/untildify.md +++ b/snippets/untildify.md @@ -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' -``` \ No newline at end of file +``` diff --git a/snippets/unzip.md b/snippets/unzip.md index 00dd4dc6a..eafef6e1b 100644 --- a/snippets/unzip.md +++ b/snippets/unzip.md @@ -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 diff --git a/snippets/unzipWith.md b/snippets/unzipWith.md index 83f6419ee..06e0c922e 100644 --- a/snippets/unzipWith.md +++ b/snippets/unzipWith.md @@ -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] ``` diff --git a/snippets/vectorAngle.md b/snippets/vectorAngle.md index 4253b2259..2e72b4eee 100644 --- a/snippets/vectorAngle.md +++ b/snippets/vectorAngle.md @@ -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)); diff --git a/snippets/vectorDistance.md b/snippets/vectorDistance.md index 830d3da32..df660c9f5 100644 --- a/snippets/vectorDistance.md +++ b/snippets/vectorDistance.md @@ -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. diff --git a/snippets/weightedAverage.md b/snippets/weightedAverage.md index 76d44dd4c..9b79e6bd3 100644 --- a/snippets/weightedAverage.md +++ b/snippets/weightedAverage.md @@ -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. diff --git a/snippets/weightedSample.md b/snippets/weightedSample.md index 409665bef..1c2f2436e 100644 --- a/snippets/weightedSample.md +++ b/snippets/weightedSample.md @@ -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) ]; }; diff --git a/snippets/when.md b/snippets/when.md index d11cf7765..9f4b5e60b 100644 --- a/snippets/when.md +++ b/snippets/when.md @@ -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`. diff --git a/snippets/without.md b/snippets/without.md index e41beaa8c..3894f4c5f 100644 --- a/snippets/without.md +++ b/snippets/without.md @@ -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)); diff --git a/snippets/wordWrap.md b/snippets/wordWrap.md index d7f107ea7..93b23f946 100644 --- a/snippets/wordWrap.md +++ b/snippets/wordWrap.md @@ -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.' ``` diff --git a/snippets/words.md b/snippets/words.md index fe8b0aa5f..bec8e94c6 100644 --- a/snippets/words.md +++ b/snippets/words.md @@ -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 diff --git a/snippets/xProd.md b/snippets/xProd.md index 0e603905b..437a03696 100644 --- a/snippets/xProd.md +++ b/snippets/xProd.md @@ -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 diff --git a/snippets/xor.md b/snippets/xor.md index f05064fed..0aa5771d9 100644 --- a/snippets/xor.md +++ b/snippets/xor.md @@ -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. diff --git a/snippets/yesterday.md b/snippets/yesterday.md index ce0fed2f2..df91649e8 100644 --- a/snippets/yesterday.md +++ b/snippets/yesterday.md @@ -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 diff --git a/snippets/zip.md b/snippets/zip.md index 6236de559..549dccf6d 100644 --- a/snippets/zip.md +++ b/snippets/zip.md @@ -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) => { diff --git a/snippets/zipObject.md b/snippets/zipObject.md index f05ba004f..ecd231169 100644 --- a/snippets/zipObject.md +++ b/snippets/zipObject.md @@ -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} -``` \ No newline at end of file +``` diff --git a/snippets/zipWith.md b/snippets/zipWith.md index 9823dadfe..16968467e 100644 --- a/snippets/zipWith.md +++ b/snippets/zipWith.md @@ -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'] ```