diff --git a/snippets/RGBToHSB.md b/snippets/RGBToHSB.md index 38410de0a..6e340be51 100644 --- a/snippets/RGBToHSB.md +++ b/snippets/RGBToHSB.md @@ -23,5 +23,6 @@ const RGBToHSB = (r, g, b) => { ``` ```js -RGBToHSB(252, 111, 48); // [18.529411764705856, 80.95238095238095, 98.82352941176471] +RGBToHSB(252, 111, 48); +// [18.529411764705856, 80.95238095238095, 98.82352941176471] ``` diff --git a/snippets/RGBToHex.md b/snippets/RGBToHex.md index ffd6f4206..2cb68f207 100644 --- a/snippets/RGBToHex.md +++ b/snippets/RGBToHex.md @@ -5,7 +5,8 @@ tags: string,math,intermediate Converts the values of RGB components to a hexadecimal color code. -- Convert given RGB parameters to hexadecimal string using bitwise left-shift operator (`<<`) and `toString(16)`, then `String.padStart(6,'0')` to get a 6-digit hexadecimal value. +- Convert given RGB parameters to hexadecimal string using bitwise left-shift operator (`<<`) and `Number.prototype.toString(16)`. +- Use `String.prototype.padStart(6,'0')` to get a 6-digit hexadecimal value. ```js const RGBToHex = (r, g, b) => ((r << 16) + (g << 8) + b).toString(16).padStart(6, '0'); diff --git a/snippets/removeNonASCII.md b/snippets/removeNonASCII.md index 72b86e5bd..ff046a3a4 100644 --- a/snippets/removeNonASCII.md +++ b/snippets/removeNonASCII.md @@ -5,7 +5,7 @@ tags: string,regexp,intermediate Removes non-printable ASCII characters. -- Use a regular expression to remove non-printable ASCII characters. +- Use `String.prototype.replace()` with a regular expression to remove non-printable ASCII characters. ```js const removeNonASCII = str => str.replace(/[^\x20-\x7E]/g, ''); diff --git a/snippets/removeWhitespace.md b/snippets/removeWhitespace.md index 1af98f2be..12aab3411 100644 --- a/snippets/removeWhitespace.md +++ b/snippets/removeWhitespace.md @@ -12,5 +12,6 @@ const removeWhitespace = str => str.replace(/\s+/g,''); ``` ```js -removeWhitespace('Lorem ipsum.\n Dolor sit amet. '); // 'Loremipsum.Dolorsitamet.' +removeWhitespace('Lorem ipsum.\n Dolor sit amet. '); +// 'Loremipsum.Dolorsitamet.' ``` diff --git a/snippets/renameKeys.md b/snippets/renameKeys.md index 088bcebb7..93c919181 100644 --- a/snippets/renameKeys.md +++ b/snippets/renameKeys.md @@ -20,5 +20,6 @@ const renameKeys = (keysMap, obj) => ```js const obj = { name: 'Bobo', job: 'Front-End Master', shoeSize: 100 }; -renameKeys({ name: 'firstName', job: 'passion' }, obj); // { firstName: 'Bobo', passion: 'Front-End Master', shoeSize: 100 } -``` \ No newline at end of file +renameKeys({ name: 'firstName', job: 'passion' }, obj); +// { firstName: 'Bobo', passion: 'Front-End Master', shoeSize: 100 } +``` diff --git a/snippets/renderElement.md b/snippets/renderElement.md index 91e7298c4..179f2ea46 100644 --- a/snippets/renderElement.md +++ b/snippets/renderElement.md @@ -5,9 +5,9 @@ tags: browser,recursion,advanced Renders the given DOM tree in the specified DOM element. -- Destructure the first argument into `type` and `props`, use `type` to determine if the given element is a text element. +- Destructure the first argument into `type` and `props`, using `type` to determine if the given element is a text element. - Based on the element's `type`, use either `Document.createTextNode()` or `Document.createElement()` to create the DOM element. -- Use `Object.keys(props`, adding attributes to the DOM element and setting event listeners, as necessary. +- Use `Object.keys()` to add attributes to the DOM element and setting event listeners, as necessary. - Use recursion to render `props.children`, if any. - Finally, use `Node.appendChild()` to append the DOM element to the specified `container`. diff --git a/snippets/round.md b/snippets/round.md index 94de65497..589a55b92 100644 --- a/snippets/round.md +++ b/snippets/round.md @@ -6,7 +6,7 @@ tags: math,intermediate Rounds a number to a specified amount of digits. - Use `Math.round()` and template literals to round the number to the specified number of digits. -- Omit the second argument, `decimals` to round to an integer. +- Omit the second argument, `decimals`, to round to an integer. ```js const round = (n, decimals = 0) => diff --git a/snippets/runAsync.md b/snippets/runAsync.md index 05ee6ec05..3dcc2a079 100644 --- a/snippets/runAsync.md +++ b/snippets/runAsync.md @@ -5,9 +5,9 @@ tags: browser,function,promise,advanced Runs a function in a separate thread by using a [Web Worker](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers), allowing long running functions to not block the UI. -- Create a new `Worker` using a `Blob` object URL, the contents of which should be the stringified version of the supplied function. +- Create a `new Worker()` using a `Blob` object URL, the contents of which should be the stringified version of the supplied function. - Immediately post the return value of calling the function back. -- Return a promise, listening for `onmessage` and `onerror` events and resolving the data posted back from the worker, or throwing an error. +- Return a `new Promise()`, listening for `onmessage` and `onerror` events and resolving the data posted back from the worker, or throwing an error. ```js const runAsync = fn => { @@ -31,7 +31,8 @@ const runAsync = fn => { const longRunningFunction = () => { let result = 0; for (let i = 0; i < 1000; i++) - for (let j = 0; j < 700; j++) for (let k = 0; k < 300; k++) result = result + i + j + k; + for (let j = 0; j < 700; j++) + for (let k = 0; k < 300; k++) result = result + i + j + k; return result; }; diff --git a/snippets/runPromisesInSeries.md b/snippets/runPromisesInSeries.md index 6fa989fd0..4c5ec56d0 100644 --- a/snippets/runPromisesInSeries.md +++ b/snippets/runPromisesInSeries.md @@ -8,10 +8,12 @@ Runs an array of promises in series. - Use `Array.prototype.reduce()` to create a promise chain, where each promise returns the next promise when resolved. ```js -const runPromisesInSeries = ps => ps.reduce((p, next) => p.then(next), Promise.resolve()); +const runPromisesInSeries = ps => + ps.reduce((p, next) => p.then(next), Promise.resolve()); ``` ```js const delay = d => new Promise(r => setTimeout(r, d)); -runPromisesInSeries([() => delay(1000), () => delay(2000)]); // Executes each promise sequentially, taking a total of 3 seconds to complete +runPromisesInSeries([() => delay(1000), () => delay(2000)]); +// Executes each promise sequentially, taking a total of 3 seconds to complete ``` diff --git a/snippets/sample.md b/snippets/sample.md index 843c1a0e1..53280485b 100644 --- a/snippets/sample.md +++ b/snippets/sample.md @@ -1,9 +1,9 @@ --- title: sample -tags: array,random,beginner +tags: array,string,random,beginner --- -Returns a random element from an array. +Gets a random element from an array. - Use `Math.random()` to generate a random number. - Multiply it by `Array.prototype.length` and round it off to the nearest whole number using `Math.floor()`. diff --git a/snippets/sampleSize.md b/snippets/sampleSize.md index 15602ee21..0d407a41f 100644 --- a/snippets/sampleSize.md +++ b/snippets/sampleSize.md @@ -3,11 +3,11 @@ title: sampleSize tags: array,random,intermediate --- -Gets `n` random elements at unique keys from `array` up to the size of `array`. +Gets `n` random elements at unique keys from an array up to the size of the array. - Shuffle the array using the [Fisher-Yates algorithm](https://github.com/30-seconds/30-seconds-of-code#shuffle). - Use `Array.prototype.slice()` to get the first `n` elements. -- Omit the second argument, `n` to get only one element at random from the array. +- Omit the second argument, `n`, to get only one element at random from the array. ```js const sampleSize = ([...arr], n = 1) => { @@ -21,6 +21,6 @@ const sampleSize = ([...arr], n = 1) => { ``` ```js -sampleSize([1, 2, 3], 2); // [3,1] -sampleSize([1, 2, 3], 4); // [2,3,1] +sampleSize([1, 2, 3], 2); // [3, 1] +sampleSize([1, 2, 3], 4); // [2, 3, 1] ``` diff --git a/snippets/scrollToTop.md b/snippets/scrollToTop.md index a7fe6eeea..a08611ede 100644 --- a/snippets/scrollToTop.md +++ b/snippets/scrollToTop.md @@ -20,5 +20,5 @@ const scrollToTop = () => { ``` ```js -scrollToTop(); +scrollToTop(); // Smooth-scrolls to the top of the page ``` diff --git a/snippets/sdbm.md b/snippets/sdbm.md index 4dd6c75a6..0aad04dc4 100644 --- a/snippets/sdbm.md +++ b/snippets/sdbm.md @@ -12,7 +12,11 @@ const sdbm = str => { let arr = str.split(''); return arr.reduce( (hashCode, currentVal) => - (hashCode = currentVal.charCodeAt(0) + (hashCode << 6) + (hashCode << 16) - hashCode), + (hashCode = + currentVal.charCodeAt(0) + + (hashCode << 6) + + (hashCode << 16) - + hashCode), 0 ); }; diff --git a/snippets/serializeCookie.md b/snippets/serializeCookie.md index 7ad7fe9cf..436f256a6 100644 --- a/snippets/serializeCookie.md +++ b/snippets/serializeCookie.md @@ -3,12 +3,13 @@ title: serializeCookie tags: browser,string,intermediate --- -Serialize a cookie name-value pair into a Set-Cookie header string. +Serializes a cookie name-value pair into a Set-Cookie header string. - Use template literals and `encodeURIComponent()` to create the appropriate string. ```js -const serializeCookie = (name, val) => `${encodeURIComponent(name)}=${encodeURIComponent(val)}`; +const serializeCookie = (name, val) => + `${encodeURIComponent(name)}=${encodeURIComponent(val)}`; ``` ```js diff --git a/snippets/serializeForm.md b/snippets/serializeForm.md index d03b297b8..4c25e37af 100644 --- a/snippets/serializeForm.md +++ b/snippets/serializeForm.md @@ -3,17 +3,21 @@ title: serializeForm tags: browser,string,intermediate --- -Encode a set of form elements as a query string. +Encodes a set of form elements as a query string. -- Use the `FormData` constructor to convert the HTML `form` to `FormData`, `Array.from()` to convert to an array, passing a map function as the second argument. +- Use the `FormData` constructor to convert the HTML `form` to `FormData`. +- Use `Array.from()` to convert to an array, passing a map function as the second argument. - Use `Array.prototype.map()` and `encodeURIComponent()` to encode each field's value. -- Use `Array.prototype.join()` with appropriate argumens to produce an appropriate query string. +- Use `Array.prototype.join()` with appropriate arguments to produce an appropriate query string. ```js const serializeForm = form => - Array.from(new FormData(form), field => field.map(encodeURIComponent).join('=')).join('&'); + Array.from(new FormData(form), field => + field.map(encodeURIComponent).join('=') + ).join('&'); ``` ```js -serializeForm(document.querySelector('#form')); // email=test%40email.com&name=Test%20Name +serializeForm(document.querySelector('#form')); +// email=test%40email.com&name=Test%20Name ``` diff --git a/snippets/setStyle.md b/snippets/setStyle.md index 814f58119..6c4c89548 100644 --- a/snippets/setStyle.md +++ b/snippets/setStyle.md @@ -5,10 +5,10 @@ tags: browser,beginner Sets the value of a CSS rule for the specified HTML element. -- Use `element.style` to set the value of the CSS rule for the specified element to `val`. +- Use `ElementCSSInlineStyle.style` to set the value of the CSS `rule` for the specified element to `val`. ```js -const setStyle = (el, ruleName, val) => (el.style[ruleName] = val); +const setStyle = (el, rule, val) => (el.style[rule] = val); ``` ```js diff --git a/snippets/shank.md b/snippets/shank.md index b244e4138..55e58a343 100644 --- a/snippets/shank.md +++ b/snippets/shank.md @@ -5,7 +5,7 @@ tags: array,intermediate Has the same functionality as [`Array.prototype.splice()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice), but returning a new array instead of mutating the original array. -- Use `Array.prototype.slice()` and `Array.prototype.concat()` to get a new array with the new contents after removing existing elements and/or adding new elements. +- Use `Array.prototype.slice()` and `Array.prototype.concat()` to get an array with the new contents after removing existing elements and/or adding new elements. - Omit the second argument, `index`, to start at `0`. - Omit the third argument, `delCount`, to remove `0` elements. - Omit the fourth argument, `elements`, in order to not add any new elements. @@ -20,7 +20,8 @@ const shank = (arr, index = 0, delCount = 0, ...elements) => ```js const names = ['alpha', 'bravo', 'charlie']; -const namesAndDelta = shank(names, 1, 0, 'delta'); // [ 'alpha', 'delta', 'bravo', 'charlie' ] +const namesAndDelta = shank(names, 1, 0, 'delta'); +// [ 'alpha', 'delta', 'bravo', 'charlie' ] const namesNoBravo = shank(names, 1, 1); // [ 'alpha', 'charlie' ] console.log(names); // ['alpha', 'bravo', 'charlie'] ``` diff --git a/snippets/show.md b/snippets/show.md index 51d6dd7ee..f4c06308e 100644 --- a/snippets/show.md +++ b/snippets/show.md @@ -12,5 +12,6 @@ const show = (...el) => [...el].forEach(e => (e.style.display = '')); ``` ```js -show(...document.querySelectorAll('img')); // Shows all elements on the page -``` \ No newline at end of file +show(...document.querySelectorAll('img')); +// Shows all elements on the page +``` diff --git a/snippets/similarity.md b/snippets/similarity.md index cfef43ca6..5319ffad7 100644 --- a/snippets/similarity.md +++ b/snippets/similarity.md @@ -5,7 +5,8 @@ tags: array,math,beginner Returns an array of elements that appear in both arrays. -- Use `Array.prototype.filter()` to remove values that are not part of `values`, determined using `Array.prototype.includes()`. +- Use `Array.prototype.includes()` to determine values that are not part of `values`. +- Use `Array.prototype.filter()` to remove them. ```js const similarity = (arr, values) => arr.filter(v => values.includes(v)); diff --git a/snippets/sleep.md b/snippets/sleep.md index 0d53a48a3..3f258dbe2 100644 --- a/snippets/sleep.md +++ b/snippets/sleep.md @@ -5,7 +5,7 @@ tags: function,promise,intermediate Delays the execution of an asynchronous function. -- Delay executing part of an `async` function, by putting it to sleep, returning a `Promise`. +- Delay executing part of an `async` function, by putting it to sleep, returning a `new Promise()`. ```js const sleep = ms => new Promise(resolve => setTimeout(resolve, ms)); diff --git a/snippets/smoothScroll.md b/snippets/smoothScroll.md index 75cdf35f5..12e73cf69 100644 --- a/snippets/smoothScroll.md +++ b/snippets/smoothScroll.md @@ -5,8 +5,8 @@ tags: browser,css,intermediate Smoothly scrolls the element on which it's called into the visible area of the browser window. -- Use `.scrollIntoView` method to scroll the element. -- Pass `{ behavior: 'smooth' }` to `.scrollIntoView` so it scrolls smoothly. +- Use `Element.scrollIntoView()` to scroll the element. +- Use `{ behavior: 'smooth' }` to scroll smoothly. ```js const smoothScroll = element => @@ -17,5 +17,6 @@ const smoothScroll = element => ```js smoothScroll('#fooBar'); // scrolls smoothly to the element with the id fooBar -smoothScroll('.fooBar'); // scrolls smoothly to the first element with a class of fooBar +smoothScroll('.fooBar'); +// scrolls smoothly to the first element with a class of fooBar ``` diff --git a/snippets/sortCharactersInString.md b/snippets/sortCharactersInString.md index 98e3024b2..2cb9c7cae 100644 --- a/snippets/sortCharactersInString.md +++ b/snippets/sortCharactersInString.md @@ -5,10 +5,12 @@ tags: string,beginner Alphabetically sorts the characters in a string. -- Use the spread operator (`...`), `Array.prototype.sort()` and `String.prototype.localeCompare()` to sort the characters in `str`, recombine using `String.prototype.join('')`. +- Use the spread operator (`...`), `Array.prototype.sort()` and `String.prototype.localeCompare()` to sort the characters in `str`. +- Recombine using `String.prototype.join('')`. ```js -const sortCharactersInString = str => [...str].sort((a, b) => a.localeCompare(b)).join(''); +const sortCharactersInString = str => + [...str].sort((a, b) => a.localeCompare(b)).join(''); ``` ```js diff --git a/snippets/sortedIndex.md b/snippets/sortedIndex.md index d716874f9..df7a53074 100644 --- a/snippets/sortedIndex.md +++ b/snippets/sortedIndex.md @@ -3,9 +3,9 @@ title: sortedIndex tags: array,math,intermediate --- -Returns the lowest index at which value should be inserted into array in order to maintain its sort order. +Finds the lowest index at which a value should be inserted into an array in order to maintain its sorting order. -- Check if the array is sorted in descending order (loosely). +- Loosely check if the array is sorted in descending order. - Use `Array.prototype.findIndex()` to find the appropriate index where the element should be inserted. ```js diff --git a/snippets/sortedIndexBy.md b/snippets/sortedIndexBy.md index 19c4d02dc..69628337f 100644 --- a/snippets/sortedIndexBy.md +++ b/snippets/sortedIndexBy.md @@ -3,16 +3,18 @@ title: sortedIndexBy tags: array,math,intermediate --- -Returns the lowest index at which value should be inserted into array in order to maintain its sort order, based on a provided iterator function. +Finds the lowest index at which a value should be inserted into an array in order to maintain its sorting order, based on the provided iterator function. -- Check if the array is sorted in descending order (loosely). +- Loosely check if the array is sorted in descending order. - Use `Array.prototype.findIndex()` to find the appropriate index where the element should be inserted, based on the iterator function `fn`. ```js const sortedIndexBy = (arr, n, fn) => { const isDescending = fn(arr[0]) > fn(arr[arr.length - 1]); const val = fn(n); - const index = arr.findIndex(el => (isDescending ? val >= fn(el) : val <= fn(el))); + const index = arr.findIndex(el => + isDescending ? val >= fn(el) : val <= fn(el) + ); return index === -1 ? arr.length : index; }; ``` diff --git a/snippets/sortedLastIndex.md b/snippets/sortedLastIndex.md index 9eda89de5..eb430a904 100644 --- a/snippets/sortedLastIndex.md +++ b/snippets/sortedLastIndex.md @@ -1,17 +1,19 @@ --- title: sortedLastIndex -tags: array,math,intermediate +tags: array,intermediate --- -Returns the highest index at which value should be inserted into array in order to maintain its sort order. +Finds the highest index at which a value should be inserted into an array in order to maintain its sort order. -- Check if the array is sorted in descending order (loosely). +- Loosely check if the array is sorted in descending order. - Use `Array.prototype.reverse()` and `Array.prototype.findIndex()` to find the appropriate last index where the element should be inserted. ```js const sortedLastIndex = (arr, n) => { const isDescending = arr[0] > arr[arr.length - 1]; - const index = arr.reverse().findIndex(el => (isDescending ? n <= el : n >= el)); + const index = arr + .reverse() + .findIndex(el => (isDescending ? n <= el : n >= el)); return index === -1 ? 0 : arr.length - index; }; ``` diff --git a/snippets/sortedLastIndexBy.md b/snippets/sortedLastIndexBy.md index 2f531b928..e9eca0a47 100644 --- a/snippets/sortedLastIndexBy.md +++ b/snippets/sortedLastIndexBy.md @@ -1,11 +1,11 @@ --- title: sortedLastIndexBy -tags: array,math,intermediate +tags: array,intermediate --- -Returns the highest index at which value should be inserted into array in order to maintain its sort order, based on a provided iterator function. +Finds the highest index at which a value should be inserted into an array in order to maintain its sort order, based on a provided iterator function. -- Check if the array is sorted in descending order (loosely). +- Loosely check if the array is sorted in descending order. - Use `Array.prototype.map()` to apply the iterator function to all elements of the array. - Use `Array.prototype.reverse()` and `Array.prototype.findIndex()` to find the appropriate last index where the element should be inserted, based on the provided iterator function. diff --git a/snippets/splitLines.md b/snippets/splitLines.md index 2bd607b8e..3d3f9dab2 100644 --- a/snippets/splitLines.md +++ b/snippets/splitLines.md @@ -1,6 +1,6 @@ --- title: splitLines -tags: string,beginner +tags: string,regexp,beginner --- Splits a multiline string into an array of lines. @@ -12,5 +12,6 @@ const splitLines = str => str.split(/\r?\n/); ``` ```js -splitLines('This\nis a\nmultiline\nstring.\n'); // ['This', 'is a', 'multiline', 'string.' , ''] +splitLines('This\nis a\nmultiline\nstring.\n'); +// ['This', 'is a', 'multiline', 'string.' , ''] ``` diff --git a/snippets/spreadOver.md b/snippets/spreadOver.md index e3916134f..b72c7c262 100644 --- a/snippets/spreadOver.md +++ b/snippets/spreadOver.md @@ -3,9 +3,9 @@ title: spreadOver tags: function,intermediate --- -Takes a variadic function and returns a closure that accepts an array of arguments to map to the inputs of the function. +Takes a variadic function and returns a function that accepts an array of arguments. -- Use closures and the spread operator (`...`) to map the array of arguments to the inputs of the function. +- Use a closure and the spread operator (`...`) to map the array of arguments to the inputs of the function. ```js const spreadOver = fn => argsArr => fn(...argsArr); diff --git a/snippets/stableSort.md b/snippets/stableSort.md index 48179245f..8902da850 100644 --- a/snippets/stableSort.md +++ b/snippets/stableSort.md @@ -4,11 +4,11 @@ tags: array,advanced --- Performs stable sorting of an array, preserving the initial indexes of items when their values are the same. -Does not mutate the original array, but returns a new array instead. - Use `Array.prototype.map()` to pair each element of the input array with its corresponding index. - Use `Array.prototype.sort()` and a `compare` function to sort the list, preserving their initial order if the items compared are equal. - Use `Array.prototype.map()` to convert back to the initial array items. +- Does not mutate the original array, but returns a new array instead. ```js const stableSort = (arr, compare) => diff --git a/snippets/standardDeviation.md b/snippets/standardDeviation.md index 9cedef9a7..f7520d171 100644 --- a/snippets/standardDeviation.md +++ b/snippets/standardDeviation.md @@ -3,17 +3,18 @@ title: standardDeviation tags: math,array,intermediate --- -Returns the standard deviation of an array of numbers. +Calculates the standard deviation of an array of numbers. -- Use `Array.prototype.reduce()` to calculate the mean, variance and the sum of the variance of the values, the variance of the values, then -- determine the standard deviation. -- You can omit the second argument to get the sample standard deviation or set it to `true` to get the population standard deviation. +- Use `Array.prototype.reduce()` to calculate the mean, variance and the sum of the variance of the values and determine the standard deviation. +- Omit the second argument, `usePopulation`, to get the sample standard deviation or set it to `true` to get the population standard deviation. ```js const standardDeviation = (arr, usePopulation = false) => { const mean = arr.reduce((acc, val) => acc + val, 0) / arr.length; return Math.sqrt( - arr.reduce((acc, val) => acc.concat((val - mean) ** 2), []).reduce((acc, val) => acc + val, 0) / + arr + .reduce((acc, val) => acc.concat((val - mean) ** 2), []) + .reduce((acc, val) => acc + val, 0) / (arr.length - (usePopulation ? 0 : 1)) ); }; @@ -21,5 +22,6 @@ const standardDeviation = (arr, usePopulation = false) => { ```js standardDeviation([10, 2, 38, 23, 38, 23, 21]); // 13.284434142114991 (sample) -standardDeviation([10, 2, 38, 23, 38, 23, 21], true); // 12.29899614287479 (population) +standardDeviation([10, 2, 38, 23, 38, 23, 21], true); +// 12.29899614287479 (population) ``` diff --git a/snippets/stringPermutations.md b/snippets/stringPermutations.md index 27b669e7f..d0524fe30 100644 --- a/snippets/stringPermutations.md +++ b/snippets/stringPermutations.md @@ -7,7 +7,8 @@ Generates all permutations of a string (contains duplicates). - Use recursion. - For each letter in the given string, create all the partial permutations for the rest of its letters. -- Use `Array.prototype.map()` to combine the letter with each partial permutation, then `Array.prototype.reduce()` to combine all permutations in one array. +- Use `Array.prototype.map()` to combine the letter with each partial permutation. +- Use `Array.prototype.reduce()` to combine all permutations in one array. - Base cases are for `String.prototype.length` equal to `2` or `1`. - ⚠️ **WARNING**: This function's execution time increases exponentially with each character. Anything more than 8 to 10 characters will cause your browser to hang as it tries to solve all the different combinations. @@ -18,12 +19,16 @@ const stringPermutations = str => { .split('') .reduce( (acc, letter, i) => - acc.concat(stringPermutations(str.slice(0, i) + str.slice(i + 1)).map(val => letter + val)), + acc.concat( + stringPermutations(str.slice(0, i) + str.slice(i + 1)).map( + val => letter + val + ) + ), [] ); }; ``` ```js -stringPermutations('abc'); // ['abc','acb','bac','bca','cab','cba'] +stringPermutations('abc'); // ['abc', 'acb', 'bac', 'bca', 'cab', 'cba'] ``` diff --git a/snippets/stringifyCircularJSON.md b/snippets/stringifyCircularJSON.md index 28dba0efa..19bc393bc 100644 --- a/snippets/stringifyCircularJSON.md +++ b/snippets/stringifyCircularJSON.md @@ -5,7 +5,7 @@ tags: object,advanced Serializes a JSON object containing circular references into a JSON format. -- Create a `WeakSet` to store and check seen values, using `WeakSet.prototype.add()` and `WeakSet.prototype.has()`. +- Create a `new WeakSet()` to store and check seen values, using `WeakSet.prototype.add()` and `WeakSet.prototype.has()`. - Use `JSON.stringify()` with a custom replacer function that omits values already in `seen`, adding new values as necessary. - ⚠️ **NOTICE:** This function finds and removes circular references, which causes circular data loss in the serialized JSON. diff --git a/snippets/subSet.md b/snippets/subSet.md index fd8b2fb26..6ff1d6041 100644 --- a/snippets/subSet.md +++ b/snippets/subSet.md @@ -3,7 +3,7 @@ title: subSet tags: array,intermediate --- -Checks if the first iterable is a subset of the second one. +Checks if the first iterable is a subset of the second one, excluding duplicate values. - Use the `new Set()` constructor to create a new `Set` object from each iterable. - Use `Array.prototype.every()` and `Set.prototype.has()` to check that each value in the first iterable is contained in the second one. diff --git a/snippets/sum.md b/snippets/sum.md index f90e81ffe..f8126150f 100644 --- a/snippets/sum.md +++ b/snippets/sum.md @@ -3,7 +3,7 @@ title: sum tags: math,array,beginner --- -Returns the sum of two or more numbers/arrays. +Calculates the sum of two or more numbers/arrays. - Use `Array.prototype.reduce()` to add each value to an accumulator, initialized with a value of `0`. @@ -14,4 +14,4 @@ const sum = (...arr) => [...arr].reduce((acc, val) => acc + val, 0); ```js sum(1, 2, 3, 4); // 10 sum(...[1, 2, 3, 4]); // 10 -``` \ No newline at end of file +``` diff --git a/snippets/sumBy.md b/snippets/sumBy.md index 90bf0539f..5383a78d4 100644 --- a/snippets/sumBy.md +++ b/snippets/sumBy.md @@ -3,9 +3,10 @@ title: sumBy tags: math,array,intermediate --- -Returns the sum of an array, after mapping each element to a value using the provided function. +Calculates the sum of an array, after mapping each element to a value using the provided function. -- Use `Array.prototype.map()` to map each element to the value returned by `fn`, `Array.prototype.reduce()` to add each value to an accumulator, initialized with a value of `0`. +- Use `Array.prototype.map()` to map each element to the value returned by `fn`. +- Use `Array.prototype.reduce()` to add each value to an accumulator, initialized with a value of `0`. ```js const sumBy = (arr, fn) => @@ -13,6 +14,6 @@ const sumBy = (arr, fn) => ``` ```js -sumBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], o => o.n); // 20 +sumBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], x => x.n); // 20 sumBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], 'n'); // 20 ``` diff --git a/snippets/sumN.md b/snippets/sumN.md index 55e1fb868..840ae35c7 100644 --- a/snippets/sumN.md +++ b/snippets/sumN.md @@ -3,7 +3,7 @@ title: sumN tags: math,beginner --- -Sums all the numbers between 1 and `n`. +Sums all the numbers between `1` and `n`. - Use the formula `(n * (n + 1)) / 2` to get the sum of all the numbers between 1 and `n`. diff --git a/snippets/sumPower.md b/snippets/sumPower.md index 60d542251..37c991351 100644 --- a/snippets/sumPower.md +++ b/snippets/sumPower.md @@ -3,9 +3,10 @@ title: sumPower tags: math,intermediate --- -Returns the sum of the powers of all the numbers from `start` to `end` (both inclusive). +Calculates the sum of the powers of all the numbers from `start` to `end` (both inclusive). -- Use `Array.prototype.fill()` to create an array of all the numbers in the target range, `Array.prototype.map()` and the exponent operator (`**`) to raise them to `power` and `Array.prototype.reduce()` to add them together. +- Use `Array.prototype.fill()` to create an array of all the numbers in the target range. +- Use `Array.prototype.map()` and the exponent operator (`**`) to raise them to `power` and `Array.prototype.reduce()` to add them together. - Omit the second argument, `power`, to use a default power of `2`. - Omit the third argument, `start`, to use a default starting value of `1`. diff --git a/snippets/superSet.md b/snippets/superSet.md index 38cc17ccd..cc6d1a356 100644 --- a/snippets/superSet.md +++ b/snippets/superSet.md @@ -3,7 +3,7 @@ title: superSet tags: array,intermediate --- -Checks if the first iterable is a superset of the second one. +Checks if the first iterable is a superset of the second one, excluding duplicate values. - Use the `new Set()` constructor to create a new `Set` object from each iterable. - Use `Array.prototype.every()` and `Set.prototype.has()` to check that each value in the second iterable is contained in the first one. diff --git a/snippets/supportsTouchEvents.md b/snippets/supportsTouchEvents.md index 0b47b373e..c92f4c576 100644 --- a/snippets/supportsTouchEvents.md +++ b/snippets/supportsTouchEvents.md @@ -5,7 +5,7 @@ tags: browser,beginner Checks if touch events are supported. -- Check if `ontouchstart` exists in `window`. +- Check if `'ontouchstart'` exists in `window`. ```js const supportsTouchEvents = () => diff --git a/snippets/symmetricDifference.md b/snippets/symmetricDifference.md index 075e26748..f2b006a47 100644 --- a/snippets/symmetricDifference.md +++ b/snippets/symmetricDifference.md @@ -5,7 +5,8 @@ tags: array,math,intermediate Returns the symmetric difference between two arrays, without filtering out duplicate values. -- Create a `Set` from each array, then use `Array.prototype.filter()` on each of them to only keep values not contained in the other. +- Create a `new Set()` from each array to get the unique values of each one. +- Use `Array.prototype.filter()` on each of them to only keep values not contained in the other. ```js const symmetricDifference = (a, b) => { diff --git a/snippets/symmetricDifferenceBy.md b/snippets/symmetricDifferenceBy.md index 5120eca17..1139c65b1 100644 --- a/snippets/symmetricDifferenceBy.md +++ b/snippets/symmetricDifferenceBy.md @@ -5,7 +5,8 @@ tags: array,intermediate Returns the symmetric difference between two arrays, after applying the provided function to each array element of both. -- Create a `Set` by applying `fn` to each array's elements, then use `Array.prototype.filter()` on each of them to only keep values not contained in the other. +- Create a `new Set()` from each array to get the unique values of each one after applying `fn` to them. +- Use `Array.prototype.filter()` on each of them to only keep values not contained in the other. ```js const symmetricDifferenceBy = (a, b, fn) => { @@ -17,5 +18,10 @@ const symmetricDifferenceBy = (a, b, fn) => { ```js symmetricDifferenceBy([2.1, 1.2], [2.3, 3.4], Math.floor); // [ 1.2, 3.4 ] -symmetricDifferenceBy([{ id: 1 }, { id: 2 }, { id: 3 }], [{ id: 1 }, { id: 2 }, { id: 4 }], i => i.id) // [{ id: 3 }, { id: 4 }] +symmetricDifferenceBy( + [{ id: 1 }, { id: 2 }, { id: 3 }], + [{ id: 1 }, { id: 2 }, { id: 4 }], + i => i.id +); +// [{ id: 3 }, { id: 4 }] ``` diff --git a/snippets/tail.md b/snippets/tail.md index 6ea7af4ad..f7354dff7 100644 --- a/snippets/tail.md +++ b/snippets/tail.md @@ -5,13 +5,13 @@ tags: array,beginner Returns all elements in an array except for the first one. -- Return `Array.prototype.slice(1)` if the array's `length` is more than `1`, otherwise, return the whole array. +- Return `Array.prototype.slice(1)` if `Array.prototype.length` is more than `1`, otherwise, return the whole array. ```js const tail = arr => (arr.length > 1 ? arr.slice(1) : arr); ``` ```js -tail([1, 2, 3]); // [2,3] +tail([1, 2, 3]); // [2, 3] tail([1]); // [1] ``` diff --git a/snippets/take.md b/snippets/take.md index 6966c5f4d..7bae3f4c6 100644 --- a/snippets/take.md +++ b/snippets/take.md @@ -3,7 +3,7 @@ title: take tags: array,beginner --- -Returns an array with n elements removed from the beginning. +Creates an array with `n` elements removed from the beginning. - Use `Array.prototype.slice()` to create a slice of the array with `n` elements taken from the beginning. diff --git a/snippets/takeRight.md b/snippets/takeRight.md index 642523fd6..3b176b2f5 100644 --- a/snippets/takeRight.md +++ b/snippets/takeRight.md @@ -3,7 +3,7 @@ title: takeRight tags: array,intermediate --- -Returns an array with n elements removed from the end. +Creates an array with `n` elements removed from the end. - Use `Array.prototype.slice()` to create a slice of the array with `n` elements taken from the end. diff --git a/snippets/takeRightWhile.md b/snippets/takeRightWhile.md index 90bcc913c..66e4646b7 100644 --- a/snippets/takeRightWhile.md +++ b/snippets/takeRightWhile.md @@ -3,9 +3,10 @@ title: takeRightWhile tags: array,intermediate --- -Removes elements from the end of an array until the passed function returns `true`. Returns the removed elements. +Removes elements from the end of an array until the passed function returns `true`. +Returns the removed elements. -- Loop through the array, using a `Array.prototype.reduceRight()` and accumulating elements while the function returns falsy value. +- Loop through the array, using `Array.prototype.reduceRight()` and accumulating elements while `func` returns falsy values. ```js const takeRightWhile = (arr, func) => diff --git a/snippets/takeWhile.md b/snippets/takeWhile.md index 852948578..1d66aa5ac 100644 --- a/snippets/takeWhile.md +++ b/snippets/takeWhile.md @@ -3,7 +3,8 @@ title: takeWhile tags: array,intermediate --- -Removes elements in an array until the passed function returns `true`. Returns the removed elements. +Removes elements in an array until the passed function returns `true`. +Returns the removed elements. - Loop through the array, using a `for...of` loop over `Array.prototype.entries()` until the returned value from the function is `true`. - Return the removed elements, using `Array.prototype.slice()`. diff --git a/snippets/timeTaken.md b/snippets/timeTaken.md index be4947b6f..65bb70233 100644 --- a/snippets/timeTaken.md +++ b/snippets/timeTaken.md @@ -3,9 +3,9 @@ title: timeTaken tags: function,beginner --- -Measures the time taken by a function to execute. +Measures the time it takes for a function to execute. -- Use `console.time()` and `console.timeEnd()` to measure the difference between the start and end times to determine how long the callback took to execute. +- Use `Console.time()` and `Console.timeEnd()` to measure the difference between the start and end times to determine how long the callback took to execute. ```js const timeTaken = callback => { diff --git a/snippets/toCamelCase.md b/snippets/toCamelCase.md index 6944f2323..31271f604 100644 --- a/snippets/toCamelCase.md +++ b/snippets/toCamelCase.md @@ -5,14 +5,17 @@ tags: string,regexp,intermediate Converts a string to camelcase. -- Break the string into words and combine them capitalizing the first letter of each word, 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()`, `String.prototype.toLowerCase()` and `String.prototype.toUpperCase()` to combine them, capitalizing the first letter of each one. ```js const toCamelCase = str => { let s = str && str - .match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g) + .match( + /[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g + ) .map(x => x.slice(0, 1).toUpperCase() + x.slice(1).toLowerCase()) .join(''); return s.slice(0, 1).toLowerCase() + s.slice(1); @@ -21,7 +24,9 @@ const toCamelCase = str => { ```js toCamelCase('some_database_field_name'); // 'someDatabaseFieldName' -toCamelCase('Some label that needs to be camelized'); // 'someLabelThatNeedsToBeCamelized' +toCamelCase('Some label that needs to be camelized'); +// 'someLabelThatNeedsToBeCamelized' toCamelCase('some-javascript-property'); // 'someJavascriptProperty' -toCamelCase('some-mixed_string with spaces_underscores-and-hyphens'); // 'someMixedStringWithSpacesUnderscoresAndHyphens' +toCamelCase('some-mixed_string with spaces_underscores-and-hyphens'); +// 'someMixedStringWithSpacesUnderscoresAndHyphens' ``` diff --git a/snippets/toCurrency.md b/snippets/toCurrency.md index d8b76dffd..dc05363bd 100644 --- a/snippets/toCurrency.md +++ b/snippets/toCurrency.md @@ -3,19 +3,27 @@ title: toCurrency tags: math,string,intermediate --- -Take a number and return specified currency formatting. +Takes a number and returns it in the specified currency formatting. - Use `Intl.NumberFormat` to enable country / currency sensitive formatting. ```js const toCurrency = (n, curr, LanguageFormat = undefined) => - Intl.NumberFormat(LanguageFormat, { style: 'currency', currency: curr }).format(n); + Intl.NumberFormat(LanguageFormat, { + style: 'currency', + currency: curr, + }).format(n); ``` ```js -toCurrency(123456.789, 'EUR'); // €123,456.79 | currency: Euro | currencyLangFormat: Local -toCurrency(123456.789, 'USD', 'en-us'); // $123,456.79 | currency: US Dollar | currencyLangFormat: English (United States) -toCurrency(123456.789, 'USD', 'fa'); // ۱۲۳٬۴۵۶٫۷۹ ؜$ | currency: US Dollar | currencyLangFormat: Farsi -toCurrency(322342436423.2435, 'JPY'); // ¥322,342,436,423 | currency: Japanese Yen | currencyLangFormat: Local -toCurrency(322342436423.2435, 'JPY', 'fi'); // 322 342 436 423 ¥ | currency: Japanese Yen | currencyLangFormat: Finnish +toCurrency(123456.789, 'EUR'); +// €123,456.79 | currency: Euro | currencyLangFormat: Local +toCurrency(123456.789, 'USD', 'en-us'); +// $123,456.79 | currency: US Dollar | currencyLangFormat: English (United States) +toCurrency(123456.789, 'USD', 'fa'); +// ۱۲۳٬۴۵۶٫۷۹ ؜$ | currency: US Dollar | currencyLangFormat: Farsi +toCurrency(322342436423.2435, 'JPY'); +// ¥322,342,436,423 | currency: Japanese Yen | currencyLangFormat: Local +toCurrency(322342436423.2435, 'JPY', 'fi'); +// 322 342 436 423 ¥ | currency: Japanese Yen | currencyLangFormat: Finnish ``` diff --git a/snippets/toDecimalMark.md b/snippets/toDecimalMark.md index 897173403..7eff8d385 100644 --- a/snippets/toDecimalMark.md +++ b/snippets/toDecimalMark.md @@ -5,7 +5,7 @@ tags: math,beginner Converts a number to a decimal mark formatted string. -- Use `Number.prototype.toLocaleString()` to convert the numbre to decimal mark format. +- Use `Number.prototype.toLocaleString()` to convert the number to decimal mark format. ```js const toDecimalMark = num => num.toLocaleString('en-US'); diff --git a/snippets/toHSLArray.md b/snippets/toHSLArray.md index 759d822a1..a4e34d3d0 100644 --- a/snippets/toHSLArray.md +++ b/snippets/toHSLArray.md @@ -13,5 +13,5 @@ const toHSLArray = hslStr => hslStr.match(/\d+/g).map(Number); ``` ```js -toHSLArray('hsl(50,10%,10%)'); // [50, 10, 10] +toHSLArray('hsl(50, 10%, 10%)'); // [50, 10, 10] ``` diff --git a/snippets/toHSLObject.md b/snippets/toHSLObject.md index ac8963993..b018e4112 100644 --- a/snippets/toHSLObject.md +++ b/snippets/toHSLObject.md @@ -17,5 +17,5 @@ const toHSLObject = hslStr => { ``` ```js -toHSLObject('hsl(50,10%,10%)'); // { hue: 50, saturation: 10, lightness: 10 } +toHSLObject('hsl(50, 10%, 10%)'); // { hue: 50, saturation: 10, lightness: 10 } ``` diff --git a/snippets/toHash.md b/snippets/toHash.md index a226ab50c..a4aa7e953 100644 --- a/snippets/toHash.md +++ b/snippets/toHash.md @@ -3,9 +3,9 @@ title: toHash tags: array,intermediate --- -Reduces a given Array-like into a value hash (keyed data store). +Reduces a given array-like into a value hash (keyed data store). -- Given an Iterable or Array-like structure, call `Array.prototype.reduce.call()` on the provided object to step over it and return an Object, keyed by the reference value. +- Given an iterable object or array-like structure, call `Array.prototype.reduce.call()` on the provided object to step over it and return an `Object`, keyed by the reference value. ```js const toHash = (object, key) => @@ -20,14 +20,20 @@ const toHash = (object, key) => toHash([4, 3, 2, 1]); // { 0: 4, 1: 3, 2: 2, 3: 1 } toHash([{ a: 'label' }], 'a'); // { label: { a: 'label' } } // A more in depth example: -let users = [{ id: 1, first: 'Jon' }, { id: 2, first: 'Joe' }, { id: 3, first: 'Moe' }]; +let users = [ + { id: 1, first: 'Jon' }, + { id: 2, first: 'Joe' }, + { id: 3, first: 'Moe' }, +]; let managers = [{ manager: 1, employees: [2, 3] }]; -// We use function here because we want a bindable reference, but a closure referencing the hash would work, too. +// We use function here because we want a bindable reference, +// but a closure referencing the hash would work, too. managers.forEach( manager => (manager.employees = manager.employees.map(function(id) { return this[id]; }, toHash(users, 'id'))) ); -managers; // [ { manager:1, employees: [ { id: 2, first: 'Joe' }, { id: 3, first: 'Moe' } ] } ] +managers; +// [ {manager:1, employees: [ {id: 2, first: 'Joe'}, {id: 3, first: 'Moe'} ] } ] ``` diff --git a/snippets/toISOStringWithTimezone.md b/snippets/toISOStringWithTimezone.md index e3488f823..67cc1a3ff 100644 --- a/snippets/toISOStringWithTimezone.md +++ b/snippets/toISOStringWithTimezone.md @@ -1,13 +1,13 @@ --- title: toISOStringWithTimezone -tags: date,math,intermediate +tags: date,intermediate --- -Returns a string in simplified extended ISO format (ISO 8601), including timezone offset. +Converts a date to extended ISO format (ISO 8601), including timezone offset. - Use `Date.prototype.getTimezoneOffset()` to get the timezone offset and reverse it, storing its sign in `diff`. -- Define a helper function, `pad`, that normalizes any passed number to an integer using `Math.floor()` and `Math.abs()` and pads it to 2 digits, using `String.prototype.padStart()`. -- Use `pad` and the built-in methods in the `Date` prototype to build the ISO 8601 string with timezone offset. +- Define a helper function, `pad`, that normalizes any passed number to an integer using `Math.floor()` and `Math.abs()` and pads it to `2` digits, using `String.prototype.padStart()`. +- Use `pad()` and the built-in methods in the `Date` prototype to build the ISO 8601 string with timezone offset. ```js const toISOStringWithTimezone = date => { diff --git a/snippets/toKebabCase.md b/snippets/toKebabCase.md index 788b4f1d4..69d415551 100644 --- a/snippets/toKebabCase.md +++ b/snippets/toKebabCase.md @@ -5,7 +5,8 @@ tags: string,regexp,intermediate Converts a string to kebab 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 toKebabCase = str => @@ -19,7 +20,9 @@ const toKebabCase = str => ```js toKebabCase('camelCase'); // 'camel-case' toKebabCase('some text'); // 'some-text' -toKebabCase('some-mixed_string With spaces_underscores-and-hyphens'); // 'some-mixed-string-with-spaces-underscores-and-hyphens' +toKebabCase('some-mixed_string With spaces_underscores-and-hyphens'); +// 'some-mixed-string-with-spaces-underscores-and-hyphens' toKebabCase('AllThe-small Things'); // 'all-the-small-things' -toKebabCase('IAmListeningToFMWhileLoadingDifferentURLOnMyBrowserAndAlsoEditingSomeXMLAndHTML'); // 'i-am-listening-to-fm-while-loading-different-url-on-my-browser-and-also-editing-xml-and-html' +toKebabCase('IAmEditingSomeXMLAndHTML'); +// 'i-am-editing-some-xml-and-html' ``` diff --git a/snippets/toPairs.md b/snippets/toPairs.md index 3685f5891..eabd08a60 100644 --- a/snippets/toPairs.md +++ b/snippets/toPairs.md @@ -3,9 +3,10 @@ title: toPairs tags: object,array,intermediate --- -Creates an array of key-value pair arrays from an object or other iterable (object, array, string, set etc.). +Creates an array of key-value pair arrays from an object or other iterable. -- Check if `Symbol.iterator` is defined and, if so, use `Array.prototype.entries()` to get an iterator for the given iterable, `Array.from()` to convert the result to an array of key-value pair arrays. +- Check if `Symbol.iterator` is defined and, if so, use `Array.prototype.entries()` to get an iterator for the given iterable. +- Use `Array.from()` to convert the result to an array of key-value pair arrays. - If `Symbol.iterator` is not defined for `obj`, use `Object.entries()` instead. ```js @@ -16,8 +17,8 @@ const toPairs = obj => ``` ```js -toPairs({ a: 1, b: 2 }); // [ ['a', 1], ['b', 2] ] -toPairs([2, 4, 8]); // [ [0, 2], [1, 4], [2, 8] ] -toPairs('shy'); // [ ['0', 's'], ['1', 'h'], ['2', 'y'] ] -toPairs(new Set(['a', 'b', 'c', 'a'])); // [ ['a', 'a'], ['b', 'b'], ['c', 'c'] ] +toPairs({ a: 1, b: 2 }); // [['a', 1], ['b', 2]] +toPairs([2, 4, 8]); // [[0, 2], [1, 4], [2, 8]] +toPairs('shy'); // [['0', 's'], ['1', 'h'], ['2', 'y']] +toPairs(new Set(['a', 'b', 'c', 'a'])); // [['a', 'a'], ['b', 'b'], ['c', 'c']] ``` diff --git a/snippets/toggleClass.md b/snippets/toggleClass.md index 87965d1e8..495501945 100644 --- a/snippets/toggleClass.md +++ b/snippets/toggleClass.md @@ -5,7 +5,7 @@ tags: browser,beginner Toggles a class for an HTML element. -- Use `element.classList.toggle()` to toggle the specified class for the element. +- Use `Element.classList` and `DOMTokenList.toggle()` to toggle the specified class for the element. ```js const toggleClass = (el, className) => el.classList.toggle(className); diff --git a/snippets/tomorrow.md b/snippets/tomorrow.md index 010e3c1b3..adac45b7a 100644 --- a/snippets/tomorrow.md +++ b/snippets/tomorrow.md @@ -5,7 +5,8 @@ tags: date,intermediate Results in a string representation of tomorrow's date. -- Use `new Date()` to get the current date, increment 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. +- Increment 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