diff --git a/snippets/objectToQueryString.md b/snippets/objectToQueryString.md index fe48abaa7..5c7758936 100644 --- a/snippets/objectToQueryString.md +++ b/snippets/objectToQueryString.md @@ -3,7 +3,7 @@ title: objectToQueryString tags: object,advanced --- -Returns a query string generated from the key-value pairs of the given object. +Generates a query string from the key-value pairs of the given object. - 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`. diff --git a/snippets/observeMutations.md b/snippets/observeMutations.md index a8a5bcecb..6220376a4 100644 --- a/snippets/observeMutations.md +++ b/snippets/observeMutations.md @@ -3,7 +3,7 @@ title: observeMutations tags: browser,event,advanced --- -Returns a new `MutationObserver` and runs the provided callback for each mutation on the specified element. +Creates 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 `Array.prototype.forEach()` to run the callback for each mutation that is observed. diff --git a/snippets/pad.md b/snippets/pad.md index 3a3f3beab..3623f57c5 100644 --- a/snippets/pad.md +++ b/snippets/pad.md @@ -3,7 +3,7 @@ title: pad tags: string,beginner --- -Pads a string on both sides with the specified character, if it's shorter than the specified length. +Pads a string on both sides with the specified character, if it's shorter than the specified `length`. - Use `String.prototype.padStart()` and `String.prototype.padEnd()` to pad both sides of the given string. - Omit the third argument, `char`, to use the whitespace character as the default padding character. diff --git a/snippets/palindrome.md b/snippets/palindrome.md index 97d6c9b48..c53153d83 100644 --- a/snippets/palindrome.md +++ b/snippets/palindrome.md @@ -3,10 +3,11 @@ title: palindrome tags: string,intermediate --- -Returns `true` if the given string is a palindrome, `false` otherwise. +Checks if the given string is a palindrome. -- Convert the string to `String.prototype.toLowerCase()` and use `String.prototype.replace()` to remove non-alphanumeric characters from it. -- Then, use the spread operator (`...`) to split the string into individual characters, `Array.prototype.reverse()`, `String.prototype.join('')` and compare it to the original, unreversed string, after converting it to `String.prototype.toLowerCase()`. +- Normalize the string to `String.prototype.toLowerCase()` and use `String.prototype.replace()` to remove non-alphanumeric characters from it. +- Use the spread operator (`...`) to split the normalized string into individual characters. +- Use `Array.prototype.reverse()`, `String.prototype.join('')` and compare the result to the normalized string. ```js const palindrome = str => { @@ -17,4 +18,4 @@ const palindrome = str => { ```js palindrome('taco cat'); // true -``` \ No newline at end of file +``` diff --git a/snippets/parseCookie.md b/snippets/parseCookie.md index 6be08dc3a..3cce879b4 100644 --- a/snippets/parseCookie.md +++ b/snippets/parseCookie.md @@ -3,7 +3,7 @@ title: parseCookie tags: browser,string,intermediate --- -Parse an HTTP Cookie header string and return an object of all cookie name-value pairs. +Parses an HTTP Cookie header string, returning an object of all cookie name-value pairs. - Use `String.prototype.split(';')` to separate key-value pairs from each other. - Use `Array.prototype.map()` and `String.prototype.split('=')` to separate keys from values in each pair. @@ -21,5 +21,6 @@ const parseCookie = str => ``` ```js -parseCookie('foo=bar; equation=E%3Dmc%5E2'); // { foo: 'bar', equation: 'E=mc^2' } +parseCookie('foo=bar; equation=E%3Dmc%5E2'); +// { foo: 'bar', equation: 'E=mc^2' } ``` diff --git a/snippets/partition.md b/snippets/partition.md index 1e45e526b..26a9c21e5 100644 --- a/snippets/partition.md +++ b/snippets/partition.md @@ -20,6 +20,10 @@ const partition = (arr, fn) => ``` ```js -const users = [{ user: 'barney', age: 36, active: false }, { user: 'fred', age: 40, active: true }]; -partition(users, o => o.active); // [[{ 'user': 'fred', 'age': 40, 'active': true }],[{ 'user': 'barney', 'age': 36, 'active': false }]] +const users = [ + { user: 'barney', age: 36, active: false }, + { user: 'fred', age: 40, active: true }, +]; +partition(users, o => o.active); +// [[{ 'user': 'fred', 'age': 40, 'active': true }],[{ 'user': 'barney', 'age': 36, 'active': false }]] ``` diff --git a/snippets/partitionBy.md b/snippets/partitionBy.md index 39f5e2aad..70fd5d746 100644 --- a/snippets/partitionBy.md +++ b/snippets/partitionBy.md @@ -3,7 +3,7 @@ title: partitionBy tags: array,object,advanced --- -Applies `fn` to each value in `arr`, splitting it each time `fn` returns a new value. +Applies `fn` to each value in `arr`, splitting it each time the provided function returns a new value. - Use `Array.prototype.reduce()` with an accumulator object that will hold the resulting array and the last value returned from `fn`. - Use `Array.prototype.push()` to add each value in `arr` to the appropriate partition in the accumulator array. diff --git a/snippets/percentile.md b/snippets/percentile.md index 8b461d9ef..99c5df2bb 100644 --- a/snippets/percentile.md +++ b/snippets/percentile.md @@ -3,13 +3,18 @@ title: percentile tags: math,intermediate --- -Uses the percentile formula to calculate how many numbers in the given array are less or equal to the given value. +Calculates the percentage of numbers in the given array that are less or equal to the given value. - Use `Array.prototype.reduce()` to calculate how many numbers are below the value and how many are the same value and apply the percentile formula. ```js const percentile = (arr, val) => - (100 * arr.reduce((acc, v) => acc + (v < val ? 1 : 0) + (v === val ? 0.5 : 0), 0)) / arr.length; + (100 * + arr.reduce( + (acc, v) => acc + (v < val ? 1 : 0) + (v === val ? 0.5 : 0), + 0 + )) / + arr.length; ``` ```js diff --git a/snippets/permutations.md b/snippets/permutations.md index 7d0c2c928..1c10d8782 100644 --- a/snippets/permutations.md +++ b/snippets/permutations.md @@ -9,7 +9,7 @@ Generates all permutations of an array's elements (contains duplicates). - For each element in the given array, create all the partial permutations for the rest of its elements. - Use `Array.prototype.map()` to combine the element with each partial permutation, then `Array.prototype.reduce()` to combine all permutations in one array. - Base cases are for `Array.prototype.length` equal to `2` or `1`. -- ⚠️ **WARNING**: This function's execution time increases exponentially with each array element. Anything more than 8 to 10 entries will cause your browser to hang as it tries to solve all the different combinations. +- ⚠️ **WARNING**: This function's execution time increases exponentially with each array element. Anything more than 8 to 10 entries may cause your browser to hang as it tries to solve all the different combinations. ```js const permutations = arr => { @@ -17,7 +17,10 @@ const permutations = arr => { return arr.reduce( (acc, item, i) => acc.concat( - permutations([...arr.slice(0, i), ...arr.slice(i + 1)]).map(val => [item, ...val]) + permutations([...arr.slice(0, i), ...arr.slice(i + 1)]).map(val => [ + item, + ...val, + ]) ), [] ); @@ -25,5 +28,6 @@ const permutations = arr => { ``` ```js -permutations([1, 33, 5]); // [ [ 1, 33, 5 ], [ 1, 5, 33 ], [ 33, 1, 5 ], [ 33, 5, 1 ], [ 5, 1, 33 ], [ 5, 33, 1 ] ] +permutations([1, 33, 5]); +// [ [1, 33, 5], [1, 5, 33], [33, 1, 5], [33, 5, 1], [5, 1, 33], [5, 33, 1] ] ``` diff --git a/snippets/pickBy.md b/snippets/pickBy.md index b609b504b..96feab053 100644 --- a/snippets/pickBy.md +++ b/snippets/pickBy.md @@ -3,10 +3,11 @@ title: pickBy tags: object,intermediate --- -Creates an object composed of the properties the given function returns truthy for. The function is invoked with two arguments: (value, key). +Creates an object composed of the properties the given function returns truthy for. - Use `Object.keys(obj)` and `Array.prototype.filter()`to remove the keys for which `fn` returns a falsy value. - 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 const pickBy = (obj, fn) => @@ -16,5 +17,6 @@ const pickBy = (obj, fn) => ``` ```js -pickBy({ a: 1, b: '2', c: 3 }, x => typeof x === 'number'); // { 'a': 1, 'c': 3 } +pickBy({ a: 1, b: '2', c: 3 }, x => typeof x === 'number'); +// { 'a': 1, 'c': 3 } ``` diff --git a/snippets/pipeAsyncFunctions.md b/snippets/pipeAsyncFunctions.md index 9eac5350b..b3a4d6b76 100644 --- a/snippets/pipeAsyncFunctions.md +++ b/snippets/pipeAsyncFunctions.md @@ -5,16 +5,16 @@ tags: function,promise,intermediate Performs left-to-right function composition for asynchronous functions. -- Use `Array.prototype.reduce()` and the spread operator (`...`) to perform function composition using `Promise.then()`. +- Use `Array.prototype.reduce()` and the spread operator (`...`) to perform function composition using `Promise.prototype.then()`. - The functions can return a combination of normal values, `Promise`s or be `async`, returning through `await`. - All functions must accept a single argument. ```js -const pipeAsyncFunctions = (...fns) => arg => fns.reduce((p, f) => p.then(f), Promise.resolve(arg)); +const pipeAsyncFunctions = (...fns) => + arg => fns.reduce((p, f) => p.then(f), Promise.resolve(arg)); ``` ```js - const sum = pipeAsyncFunctions( x => x + 1, x => new Promise(resolve => setTimeout(() => resolve(x + 2), 1000)), diff --git a/snippets/pipeFunctions.md b/snippets/pipeFunctions.md index 37fffb4f7..d1612dbfe 100644 --- a/snippets/pipeFunctions.md +++ b/snippets/pipeFunctions.md @@ -9,7 +9,8 @@ Performs left-to-right function composition. - The first (leftmost) function can accept one or more arguments; the remaining functions must be unary. ```js -const pipeFunctions = (...fns) => fns.reduce((f, g) => (...args) => g(f(...args))); +const pipeFunctions = (...fns) => + fns.reduce((f, g) => (...args) => g(f(...args))); ``` ```js diff --git a/snippets/pluck.md b/snippets/pluck.md index 27b3ccb97..d84235a6a 100644 --- a/snippets/pluck.md +++ b/snippets/pluck.md @@ -16,7 +16,7 @@ const simpsons = [ { name: 'lisa', age: 8 }, { name: 'homer', age: 36 }, { name: 'marge', age: 34 }, - { name: 'bart', age: 10 }, + { name: 'bart', age: 10 } ]; pluck(simpsons, 'age'); // [8, 36, 34, 10] ``` diff --git a/snippets/pluralize.md b/snippets/pluralize.md index 7065b5620..173be1119 100644 --- a/snippets/pluralize.md +++ b/snippets/pluralize.md @@ -1,20 +1,22 @@ --- title: pluralize -tags: string,intermediate +tags: string,advanced --- -Returns the singular or plural form of the word based on the input number. If the first argument is an `object`, it will use a closure by returning a function that can auto-pluralize words that don't simply end in `s` if the supplied dictionary contains the word. +Returns the singular or plural form of the word based on the input number, using an optional dictionary if supplied. +- Use a closure to define a function that pluralizes the given `word` based on the value of `num`. - If `num` is either `-1` or `1`, return the singular form of the word. -- If `num` is any other number, return the plural form. -- Omit the third argument to use the default of the singular word + `s`, or supply a custom pluralized word when necessary. -- If the first argument is an `object`, utilize a closure by returning a function which can use the supplied dictionary to resolve the correct plural form of the word. +- If `num` is any other number, return the `plural` form. +- Omit the third argument, `plural`, to use the default of the singular word + `s`, or supply a custom pluralized `word` when necessary. +- If the first argument is an `object`, return a function which can use the supplied dictionary to resolve the correct plural form of the word. ```js const pluralize = (val, word, plural = word + 's') => { const _pluralize = (num, word, plural = word + 's') => [1, -1].includes(Number(num)) ? word : plural; - if (typeof val === 'object') return (num, word) => _pluralize(num, word, val[word]); + if (typeof val === 'object') + return (num, word) => _pluralize(num, word, val[word]); return _pluralize(val, word, plural); }; ``` diff --git a/snippets/powerset.md b/snippets/powerset.md index ec9d010d3..823c60ab4 100644 --- a/snippets/powerset.md +++ b/snippets/powerset.md @@ -8,7 +8,8 @@ Returns the powerset of a given array of numbers. - Use `Array.prototype.reduce()` combined with `Array.prototype.map()` to iterate over elements and combine into an array containing all combinations. ```js -const powerset = arr => arr.reduce((a, v) => a.concat(a.map(r => [v].concat(r))), [[]]); +const powerset = arr => + arr.reduce((a, v) => a.concat(a.map(r => [v].concat(r))), [[]]); ``` ```js diff --git a/snippets/prefersDarkColorScheme.md b/snippets/prefersDarkColorScheme.md index 0483c6e47..c35085da0 100644 --- a/snippets/prefersDarkColorScheme.md +++ b/snippets/prefersDarkColorScheme.md @@ -3,13 +3,15 @@ title: prefersDarkColorScheme tags: browser,intermediate --- -Returns `true` if the user color scheme preference is `dark`, `false` otherwise. +Checks if the user color scheme preference is `dark`. - Use `Window.matchMedia()` with the appropriate media query to check the user color scheme preference. ```js const prefersDarkColorScheme = () => - window && window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches; + window && + window.matchMedia && + window.matchMedia('(prefers-color-scheme: dark)').matches; ``` ```js diff --git a/snippets/prefersLightColorScheme.md b/snippets/prefersLightColorScheme.md index 13752b088..e6127b15e 100644 --- a/snippets/prefersLightColorScheme.md +++ b/snippets/prefersLightColorScheme.md @@ -3,13 +3,15 @@ title: prefersLightColorScheme tags: browser,intermediate --- -Returns `true` if the user color scheme preference is `light`, `false` otherwise. +Checks if the user color scheme preference is `light`. - Use `Window.matchMedia()` with the appropriate media query to check the user color scheme preference. ```js const prefersLightColorScheme = () => - window && window.matchMedia && window.matchMedia('(prefers-color-scheme: light)').matches; + window && + window.matchMedia && + window.matchMedia('(prefers-color-scheme: light)').matches; ``` ```js diff --git a/snippets/prefix.md b/snippets/prefix.md index da611b477..af88e76ba 100644 --- a/snippets/prefix.md +++ b/snippets/prefix.md @@ -3,7 +3,7 @@ title: prefix tags: browser,intermediate --- -Returns the prefixed version (if necessary) of a CSS property that the browser supports. +Prefixes a CSS property based on the current browser. - Use `Array.prototype.findIndex()` on an array of vendor prefix strings to test if `Document.body` has one of them defined in its `CSSStyleDeclaration` object, otherwise return `null`. - Use `String.prototype.charAt()` and `String.prototype.toUpperCase()` to capitalize the property, which will be appended to the vendor prefix string. @@ -13,12 +13,15 @@ const prefix = prop => { const capitalizedProp = prop.charAt(0).toUpperCase() + prop.slice(1); const prefixes = ['', 'webkit', 'moz', 'ms', 'o']; const i = prefixes.findIndex( - prefix => typeof document.body.style[prefix ? prefix + capitalizedProp : prop] !== 'undefined' + prefix => + typeof document.body.style[prefix ? prefix + capitalizedProp : prop] !== + 'undefined' ); return i !== -1 ? (i === 0 ? prop : prefixes[i] + capitalizedProp) : null; }; ``` ```js -prefix('appearance'); // 'appearance' on a supported browser, otherwise 'webkitAppearance', 'mozAppearance', 'msAppearance' or 'oAppearance' +prefix('appearance'); +// 'appearance' on a supported browser, otherwise 'webkitAppearance', 'mozAppearance', 'msAppearance' or 'oAppearance' ``` diff --git a/snippets/prettyBytes.md b/snippets/prettyBytes.md index b75e93614..334634e5b 100644 --- a/snippets/prettyBytes.md +++ b/snippets/prettyBytes.md @@ -15,8 +15,13 @@ Converts a number in bytes to a human-readable string. const prettyBytes = (num, precision = 3, addSpace = true) => { const UNITS = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']; if (Math.abs(num) < 1) return num + (addSpace ? ' ' : '') + UNITS[0]; - const exponent = Math.min(Math.floor(Math.log10(num < 0 ? -num : num) / 3), UNITS.length - 1); - const n = Number(((num < 0 ? -num : num) / 1000 ** exponent).toPrecision(precision)); + const exponent = Math.min( + Math.floor(Math.log10(num < 0 ? -num : num) / 3), + UNITS.length - 1 + ); + const n = Number( + ((num < 0 ? -num : num) / 1000 ** exponent).toPrecision(precision) + ); return (num < 0 ? '-' : '') + n + (addSpace ? ' ' : '') + UNITS[exponent]; }; ``` diff --git a/snippets/primes.md b/snippets/primes.md index 946e4b022..0f21b1c48 100644 --- a/snippets/primes.md +++ b/snippets/primes.md @@ -19,5 +19,5 @@ const primes = num => { ``` ```js -primes(10); // [2,3,5,7] +primes(10); // [2, 3, 5, 7] ``` diff --git a/snippets/prod.md b/snippets/prod.md index 0c8dd2b74..49eb3d95b 100644 --- a/snippets/prod.md +++ b/snippets/prod.md @@ -3,7 +3,7 @@ title: prod tags: math,array,intermediate --- -Returns the product of two or more numbers/arrays. +Calculates the product of two or more numbers/arrays. - Use `Array.prototype.reduce()` to multiply each value with an accumulator, initialized with a value of `1`. diff --git a/snippets/promisify.md b/snippets/promisify.md index adefbc2e4..b67267e66 100644 --- a/snippets/promisify.md +++ b/snippets/promisify.md @@ -6,8 +6,8 @@ tags: function,promise,intermediate Converts an asynchronous function to return a promise. - Use currying to return a function returning a `Promise` that calls the original function. -- Use the `...rest` operator to pass in all the parameters. -- *In Node 8+, you can use [`util.promisify`](https://nodejs.org/api/util.html#util_util_promisify_original)* +- Use the rest operator (`...`) to pass in all the parameters. +- **Note:** In Node 8+, you can use [`util.promisify`](https://nodejs.org/api/util.html#util_util_promisify_original). ```js const promisify = func => (...args) => @@ -18,5 +18,5 @@ const promisify = func => (...args) => ```js const delay = promisify((d, cb) => setTimeout(cb, d)); -delay(2000).then(() => console.log('Hi!')); // // Promise resolves after 2s +delay(2000).then(() => console.log('Hi!')); // Promise resolves after 2s ``` diff --git a/snippets/pull.md b/snippets/pull.md index 999d7b28e..86b7ffa6c 100644 --- a/snippets/pull.md +++ b/snippets/pull.md @@ -6,7 +6,8 @@ tags: array,intermediate Mutates the original array to filter out the values specified. - Use `Array.prototype.filter()` and `Array.prototype.includes()` to pull out the values that are not needed. -- Use `Array.prototype.length = 0` to mutate the passed in an array by resetting it's length to zero and `Array.prototype.push()` to re-populate it with only the pulled values. +- Set `Array.prototype.length` to mutate the passed in an array by resetting its length to `0`. +- Use `Array.prototype.push()` to re-populate it with only the pulled values. ```js const pull = (arr, ...args) => { diff --git a/snippets/pullAtIndex.md b/snippets/pullAtIndex.md index 26f6aad50..e01feb82d 100644 --- a/snippets/pullAtIndex.md +++ b/snippets/pullAtIndex.md @@ -4,10 +4,12 @@ tags: array,advanced --- Mutates the original array to filter out the values at the specified indexes. +Returns the removed elements. - Use `Array.prototype.filter()` and `Array.prototype.includes()` to pull out the values that are not needed. -- Use `Array.prototype.length = 0` to mutate the passed in an array by resetting it's length to zero and `Array.prototype.push()` to re-populate it with only the pulled values. -- Use `Array.prototype.push()` to keep track of pulled values +- Set `Array.prototype.length` to mutate the passed in an array by resetting its length to `0`. +- Use `Array.prototype.push()` to re-populate it with only the pulled values. +- Use `Array.prototype.push()` to keep track of pulled values. ```js const pullAtIndex = (arr, pullArr) => { @@ -23,5 +25,6 @@ const pullAtIndex = (arr, pullArr) => { ```js let myArray = ['a', 'b', 'c', 'd']; -let pulled = pullAtIndex(myArray, [1, 3]); // myArray = [ 'a', 'c' ] , pulled = [ 'b', 'd' ] +let pulled = pullAtIndex(myArray, [1, 3]); +// myArray = [ 'a', 'c' ] , pulled = [ 'b', 'd' ] ``` diff --git a/snippets/pullAtValue.md b/snippets/pullAtValue.md index 018e52d66..bc470f561 100644 --- a/snippets/pullAtValue.md +++ b/snippets/pullAtValue.md @@ -3,16 +3,20 @@ title: pullAtValue tags: array,advanced --- -Mutates the original array to filter out the values specified. Returns the removed elements. +Mutates the original array to filter out the values specified. +Returns the removed elements. - Use `Array.prototype.filter()` and `Array.prototype.includes()` to pull out the values that are not needed. -- Use `Array.prototype.length = 0` to mutate the passed in an array by resetting it's length to zero and `Array.prototype.push()` to re-populate it with only the pulled values. -- Use `Array.prototype.push()` to keep track of pulled values +- Set `Array.prototype.length` to mutate the passed in an array by resetting its length to `0`. +- Use `Array.prototype.push()` to re-populate it with only the pulled values. +- Use `Array.prototype.push()` to keep track of pulled values. ```js const pullAtValue = (arr, pullArr) => { let removed = [], - pushToRemove = arr.forEach((v, i) => (pullArr.includes(v) ? removed.push(v) : v)), + pushToRemove = arr.forEach((v, i) => + pullArr.includes(v) ? removed.push(v) : v + ), mutateTo = arr.filter((v, i) => !pullArr.includes(v)); arr.length = 0; mutateTo.forEach(v => arr.push(v)); @@ -22,5 +26,6 @@ const pullAtValue = (arr, pullArr) => { ```js let myArray = ['a', 'b', 'c', 'd']; -let pulled = pullAtValue(myArray, ['b', 'd']); // myArray = [ 'a', 'c' ] , pulled = [ 'b', 'd' ] +let pulled = pullAtValue(myArray, ['b', 'd']); +// myArray = [ 'a', 'c' ] , pulled = [ 'b', 'd' ] ``` diff --git a/snippets/pullBy.md b/snippets/pullBy.md index fb5ae4212..bfe0da135 100644 --- a/snippets/pullBy.md +++ b/snippets/pullBy.md @@ -5,10 +5,11 @@ tags: array,advanced Mutates the original array to filter out the values specified, based on a given iterator function. -- Check if the last argument provided in a function. +- Check if the last argument provided is a function. - Use `Array.prototype.map()` to apply the iterator function `fn` to all array elements. - Use `Array.prototype.filter()` and `Array.prototype.includes()` to pull out the values that are not needed. -- Use `Array.prototype.length = 0` to mutate the passed in an array by resetting it's length to zero and `Array.prototype.push()` to re-populate it with only the pulled values. +- Set `Array.prototype.length` to mutate the passed in an array by resetting its length to `0`. +- Use `Array.prototype.push()` to re-populate it with only the pulled values. ```js const pullBy = (arr, ...args) => { diff --git a/snippets/quarterOfYear.md b/snippets/quarterOfYear.md index 57f81b726..b53d5e0b1 100644 --- a/snippets/quarterOfYear.md +++ b/snippets/quarterOfYear.md @@ -7,13 +7,13 @@ Returns the quarter and year to which the supplied date belongs to. - Use `Date.prototype.getMonth()` to get the current month in the range (0, 11), add `1` to map it to the range (1, 12). - Use `Math.ceil()` and divide the month by `3` to get the current quarter. -- Use `Date.prototype.getFullYear()` to get the year from the given date. +- Use `Date.prototype.getFullYear()` to get the year from the given `date`. - Omit the argument, `date`, to use the current date by default. ```js const quarterOfYear = (date = new Date()) => [ Math.ceil((date.getMonth() + 1) / 3), - date.getFullYear(), + date.getFullYear() ]; ``` diff --git a/snippets/randomAlphaNumeric.md b/snippets/randomAlphaNumeric.md index 27a02f569..241ca08be 100644 --- a/snippets/randomAlphaNumeric.md +++ b/snippets/randomAlphaNumeric.md @@ -3,7 +3,7 @@ title: randomAlphaNumeric tags: string,random,advanced --- -Returns a random string with the specified length. +Generates a random string with the specified length. - Use `Array.from()` to create a new array with the specified `length`. - Use `Math.random()` generate a random floating-point number, `Number.prototype.toString(36)` to convert it to an alphanumeric string. diff --git a/snippets/randomHexColorCode.md b/snippets/randomHexColorCode.md index f07c9d22d..d7a70f7f2 100644 --- a/snippets/randomHexColorCode.md +++ b/snippets/randomHexColorCode.md @@ -5,8 +5,8 @@ tags: math,random,beginner Generates a random hexadecimal color code. -- Use `Math.random` to generate a random 24-bit(6x4bits) hexadecimal number. -- Use bit shifting and then convert it to an hexadecimal String using `toString(16)`. +- Use `Math.rando()m` to generate a random 24-bit (6 * 4bits) hexadecimal number. +- Use bit shifting and then convert it to an hexadecimal string using `Number.prototype.toString(16)`. ```js const randomHexColorCode = () => { diff --git a/snippets/randomIntArrayInRange.md b/snippets/randomIntArrayInRange.md index 618cfbb51..19571c193 100644 --- a/snippets/randomIntArrayInRange.md +++ b/snippets/randomIntArrayInRange.md @@ -3,13 +3,17 @@ title: randomIntArrayInRange tags: math,random,intermediate --- -Returns an array of n random integers in the specified range. +Generates an array of `n` random integers in the specified range. -- Use `Array.from()` to create an empty array of the specific length, `Math.random()` to generate a random number and map it to the desired range, using `Math.floor()` to make it an integer. +- Use `Array.from()` to create an empty array of the specific length. +- Use `Math.random()` to generate random numbers and map them to the desired range, using `Math.floor()` to make them integers. ```js const randomIntArrayInRange = (min, max, n = 1) => - Array.from({ length: n }, () => Math.floor(Math.random() * (max - min + 1)) + min); + Array.from( + { length: n }, + () => Math.floor(Math.random() * (max - min + 1)) + min + ); ``` ```js diff --git a/snippets/randomIntegerInRange.md b/snippets/randomIntegerInRange.md index dc2183656..8b63fe64e 100644 --- a/snippets/randomIntegerInRange.md +++ b/snippets/randomIntegerInRange.md @@ -3,12 +3,14 @@ title: randomIntegerInRange tags: math,random,beginner --- -Returns a random integer in the specified range. +Generates a random integer in the specified range. -- Use `Math.random()` to generate a random number and map it to the desired range, using `Math.floor()` to make it an integer. +- Use `Math.random()` to generate a random number and map it to the desired range. +- Use `Math.floor()` to make it an integer. ```js -const randomIntegerInRange = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min; +const randomIntegerInRange = (min, max) => + Math.floor(Math.random() * (max - min + 1)) + min; ``` ```js diff --git a/snippets/randomNumberInRange.md b/snippets/randomNumberInRange.md index fcb6fbe90..ba177258f 100644 --- a/snippets/randomNumberInRange.md +++ b/snippets/randomNumberInRange.md @@ -3,7 +3,7 @@ title: randomNumberInRange tags: math,random,beginner --- -Returns a random number in the specified range. +Generates a random number in the specified range. - Use `Math.random()` to generate a random value, map it to the desired range using multiplication. diff --git a/snippets/readFileLines.md b/snippets/readFileLines.md index 37f1e61c3..b1d7004eb 100644 --- a/snippets/readFileLines.md +++ b/snippets/readFileLines.md @@ -1,13 +1,13 @@ --- title: readFileLines -tags: node,beginner +tags: node,array,beginner --- Returns an array of lines from the specified file. -- Use `readFileSync` function in `fs` node package to create a `Buffer` from a file. -- Convert buffer to string using `toString(encoding)` function. -- Use `split(\n)` to create an array of lines from the contents of the file. +- Use `fs.readFileSync()` to create a `Buffer` from a file. +- Convert buffer to string using `buf.toString(encoding)` function. +- Use `String.prototype.split(\n)` to create an array of lines from the contents of the file. ```js const fs = require('fs'); diff --git a/snippets/rearg.md b/snippets/rearg.md index 9a0f9e6ff..2c9ea483b 100644 --- a/snippets/rearg.md +++ b/snippets/rearg.md @@ -5,7 +5,8 @@ tags: function,intermediate Creates a function that invokes the provided function with its arguments arranged according to the specified indexes. -- Use `Array.prototype.map()` to reorder arguments based on `indexes` in combination with the spread operator (`...`) to pass the transformed arguments to `fn`. +- Use `Array.prototype.map()` to reorder arguments based on `indexes`. +- Use the spread operator (`...`) to pass the transformed arguments to `fn`. ```js const rearg = (fn, indexes) => (...args) => fn(...indexes.map(i => args[i])); diff --git a/snippets/recordAnimationFrames.md b/snippets/recordAnimationFrames.md index f0eb004cb..231333dc5 100644 --- a/snippets/recordAnimationFrames.md +++ b/snippets/recordAnimationFrames.md @@ -1,6 +1,6 @@ --- title: recordAnimationFrames -tags: browser,intermediate +tags: browser,recursion,intermediate --- Invokes the provided callback on each animation frame. @@ -37,8 +37,10 @@ const recordAnimationFrames = (callback, autoStart = true) => { ```js const cb = () => console.log('Animation frame fired'); -const recorder = recordAnimationFrames(cb); // logs 'Animation frame fired' on each animation frame +const recorder = recordAnimationFrames(cb); +// logs 'Animation frame fired' on each animation frame recorder.stop(); // stops logging recorder.start(); // starts again -const recorder2 = recordAnimationFrames(cb, false); // `start` needs to be explicitly called to begin recording frames +const recorder2 = recordAnimationFrames(cb, false); +// `start` needs to be explicitly called to begin recording frames ``` diff --git a/snippets/reduceSuccessive.md b/snippets/reduceSuccessive.md index 5d7e36e87..d5c794705 100644 --- a/snippets/reduceSuccessive.md +++ b/snippets/reduceSuccessive.md @@ -9,9 +9,13 @@ Applies a function against an accumulator and each element in the array (from le ```js const reduceSuccessive = (arr, fn, acc) => - arr.reduce((res, val, i, arr) => (res.push(fn(res.slice(-1)[0], val, i, arr)), res), [acc]); + arr.reduce( + (res, val, i, arr) => (res.push(fn(res.slice(-1)[0], val, i, arr)), res), + [acc] + ); ``` ```js -reduceSuccessive([1, 2, 3, 4, 5, 6], (acc, val) => acc + val, 0); // [0, 1, 3, 6, 10, 15, 21] +reduceSuccessive([1, 2, 3, 4, 5, 6], (acc, val) => acc + val, 0); +// [0, 1, 3, 6, 10, 15, 21] ``` diff --git a/snippets/reduceWhich.md b/snippets/reduceWhich.md index 4b8b696b7..79f8381e1 100644 --- a/snippets/reduceWhich.md +++ b/snippets/reduceWhich.md @@ -3,7 +3,7 @@ title: reduceWhich tags: array,intermediate --- -Returns the minimum/maximum value of an array, after applying the provided function to set comparing rule. +Returns the minimum/maximum value of an array, after applying the provided function to set the comparing rule. - Use `Array.prototype.reduce()` in combination with the `comparator` function to get the appropriate element in the array. - You can omit the second parameter, `comparator`, to use the default one that returns the minimum element in the array. diff --git a/snippets/reducedFilter.md b/snippets/reducedFilter.md index 3328baf62..bc7fc8fd2 100644 --- a/snippets/reducedFilter.md +++ b/snippets/reducedFilter.md @@ -3,10 +3,11 @@ title: reducedFilter tags: array,intermediate --- -Filter an array of objects based on a condition while also filtering out unspecified keys. +Filters an array of objects based on a condition while also filtering out unspecified keys. - Use `Array.prototype.filter()` to filter the array based on the predicate `fn` so that it returns the objects for which the condition returned a truthy value. -- On the filtered array, use `Array.prototype.map()` to return the new object using `Array.prototype.reduce()` to filter out the keys which were not supplied as the `keys` argument. +- On the filtered array, use `Array.prototype.map()` to return the new object. +- Use `Array.prototype.reduce()` to filter out the keys which were not supplied as the `keys` argument. ```js const reducedFilter = (data, keys, fn) => @@ -31,6 +32,6 @@ const data = [ age: 50 } ]; - -reducedFilter(data, ['id', 'name'], item => item.age > 24); // [{ id: 2, name: 'mike'}] +reducedFilter(data, ['id', 'name'], item => item.age > 24); +// [{ id: 2, name: 'mike'}] ``` diff --git a/snippets/reject.md b/snippets/reject.md index 845c2ac5b..5425db7de 100644 --- a/snippets/reject.md +++ b/snippets/reject.md @@ -5,7 +5,7 @@ tags: array,beginner Filters an array's values based on a predicate function, returning only values for which the predicate function returns `false`. -- Use `Array.prototype.filter()` in combination with the predicate function, `pred`, to return only the values for which `pred()` returns `false`. +- Use `Array.prototype.filter()` in combination with the predicate function, `pred`, to return only the values for which it returns `false`. ```js const reject = (pred, array) => array.filter((...args) => !pred(...args)); @@ -13,5 +13,6 @@ const reject = (pred, array) => array.filter((...args) => !pred(...args)); ```js reject(x => x % 2 === 0, [1, 2, 3, 4, 5]); // [1, 3, 5] -reject(word => word.length > 4, ['Apple', 'Pear', 'Kiwi', 'Banana']); // ['Pear', 'Kiwi'] +reject(word => word.length > 4, ['Apple', 'Pear', 'Kiwi', 'Banana']); +// ['Pear', 'Kiwi'] ``` diff --git a/snippets/remove.md b/snippets/remove.md index 618e1028b..cc7bb4827 100644 --- a/snippets/remove.md +++ b/snippets/remove.md @@ -5,8 +5,9 @@ tags: array,intermediate Mutates an array by removing elements for which the given function returns `false`. -- Use `Array.prototype.filter()` to find array elements that return truthy values and `Array.prototype.reduce()` to remove elements using `Array.prototype.splice()`. -- The `func` is invoked with three arguments (`value, index, array`). +- Use `Array.prototype.filter()` to find array elements that return truthy values. +- Use `Array.prototype.reduce()` to remove elements using `Array.prototype.splice()`. +- The callback function is invoked with three arguments (value, index, array). ```js diff --git a/snippets/removeAccents.md b/snippets/removeAccents.md index 5e531f265..b6eb6626e 100644 --- a/snippets/removeAccents.md +++ b/snippets/removeAccents.md @@ -9,7 +9,8 @@ Removes accents from strings. - Use `String.prototype.replace()` to replace diacritical marks in the given Unicode range by empty strings. ```js -const removeAccents = str => str.normalize('NFD').replace(/[\u0300-\u036f]/g, ''); +const removeAccents = str => + str.normalize('NFD').replace(/[\u0300-\u036f]/g, ''); ``` ```js