Update snippet descriptions

This commit is contained in:
Isabelle Viktoria Maciohsek
2020-10-22 20:24:30 +03:00
parent d35575373f
commit 5cb69e3c5c
58 changed files with 195 additions and 126 deletions

View File

@ -23,5 +23,6 @@ const RGBToHSB = (r, g, b) => {
``` ```
```js ```js
RGBToHSB(252, 111, 48); // [18.529411764705856, 80.95238095238095, 98.82352941176471] RGBToHSB(252, 111, 48);
// [18.529411764705856, 80.95238095238095, 98.82352941176471]
``` ```

View File

@ -5,7 +5,8 @@ tags: string,math,intermediate
Converts the values of RGB components to a hexadecimal color code. 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 ```js
const RGBToHex = (r, g, b) => ((r << 16) + (g << 8) + b).toString(16).padStart(6, '0'); const RGBToHex = (r, g, b) => ((r << 16) + (g << 8) + b).toString(16).padStart(6, '0');

View File

@ -5,7 +5,7 @@ tags: string,regexp,intermediate
Removes non-printable ASCII characters. 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 ```js
const removeNonASCII = str => str.replace(/[^\x20-\x7E]/g, ''); const removeNonASCII = str => str.replace(/[^\x20-\x7E]/g, '');

View File

@ -12,5 +12,6 @@ const removeWhitespace = str => str.replace(/\s+/g,'');
``` ```
```js ```js
removeWhitespace('Lorem ipsum.\n Dolor sit amet. '); // 'Loremipsum.Dolorsitamet.' removeWhitespace('Lorem ipsum.\n Dolor sit amet. ');
// 'Loremipsum.Dolorsitamet.'
``` ```

View File

@ -20,5 +20,6 @@ const renameKeys = (keysMap, obj) =>
```js ```js
const obj = { name: 'Bobo', job: 'Front-End Master', shoeSize: 100 }; const obj = { name: 'Bobo', job: 'Front-End Master', shoeSize: 100 };
renameKeys({ name: 'firstName', job: 'passion' }, obj); // { firstName: 'Bobo', passion: 'Front-End Master', shoeSize: 100 } renameKeys({ name: 'firstName', job: 'passion' }, obj);
``` // { firstName: 'Bobo', passion: 'Front-End Master', shoeSize: 100 }
```

View File

@ -5,9 +5,9 @@ tags: browser,recursion,advanced
Renders the given DOM tree in the specified DOM element. 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. - 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. - Use recursion to render `props.children`, if any.
- Finally, use `Node.appendChild()` to append the DOM element to the specified `container`. - Finally, use `Node.appendChild()` to append the DOM element to the specified `container`.

View File

@ -6,7 +6,7 @@ tags: math,intermediate
Rounds a number to a specified amount of digits. 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. - 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 ```js
const round = (n, decimals = 0) => const round = (n, decimals = 0) =>

View File

@ -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. 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. - 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 ```js
const runAsync = fn => { const runAsync = fn => {
@ -31,7 +31,8 @@ const runAsync = fn => {
const longRunningFunction = () => { const longRunningFunction = () => {
let result = 0; let result = 0;
for (let i = 0; i < 1000; i++) 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; return result;
}; };

View File

@ -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. - Use `Array.prototype.reduce()` to create a promise chain, where each promise returns the next promise when resolved.
```js ```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 ```js
const delay = d => new Promise(r => setTimeout(r, d)); 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
``` ```

View File

@ -1,9 +1,9 @@
--- ---
title: sample 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. - 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()`. - Multiply it by `Array.prototype.length` and round it off to the nearest whole number using `Math.floor()`.

View File

@ -3,11 +3,11 @@ title: sampleSize
tags: array,random,intermediate 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). - 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. - 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 ```js
const sampleSize = ([...arr], n = 1) => { const sampleSize = ([...arr], n = 1) => {
@ -21,6 +21,6 @@ const sampleSize = ([...arr], n = 1) => {
``` ```
```js ```js
sampleSize([1, 2, 3], 2); // [3,1] sampleSize([1, 2, 3], 2); // [3, 1]
sampleSize([1, 2, 3], 4); // [2,3,1] sampleSize([1, 2, 3], 4); // [2, 3, 1]
``` ```

View File

@ -20,5 +20,5 @@ const scrollToTop = () => {
``` ```
```js ```js
scrollToTop(); scrollToTop(); // Smooth-scrolls to the top of the page
``` ```

View File

@ -12,7 +12,11 @@ const sdbm = str => {
let arr = str.split(''); let arr = str.split('');
return arr.reduce( return arr.reduce(
(hashCode, currentVal) => (hashCode, currentVal) =>
(hashCode = currentVal.charCodeAt(0) + (hashCode << 6) + (hashCode << 16) - hashCode), (hashCode =
currentVal.charCodeAt(0) +
(hashCode << 6) +
(hashCode << 16) -
hashCode),
0 0
); );
}; };

View File

@ -3,12 +3,13 @@ title: serializeCookie
tags: browser,string,intermediate 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. - Use template literals and `encodeURIComponent()` to create the appropriate string.
```js ```js
const serializeCookie = (name, val) => `${encodeURIComponent(name)}=${encodeURIComponent(val)}`; const serializeCookie = (name, val) =>
`${encodeURIComponent(name)}=${encodeURIComponent(val)}`;
``` ```
```js ```js

View File

@ -3,17 +3,21 @@ title: serializeForm
tags: browser,string,intermediate 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.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 ```js
const serializeForm = form => 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 ```js
serializeForm(document.querySelector('#form')); // email=test%40email.com&name=Test%20Name serializeForm(document.querySelector('#form'));
// email=test%40email.com&name=Test%20Name
``` ```

View File

@ -5,10 +5,10 @@ tags: browser,beginner
Sets the value of a CSS rule for the specified HTML element. 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 ```js
const setStyle = (el, ruleName, val) => (el.style[ruleName] = val); const setStyle = (el, rule, val) => (el.style[rule] = val);
``` ```
```js ```js

View File

@ -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. 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 second argument, `index`, to start at `0`.
- Omit the third argument, `delCount`, to remove `0` elements. - Omit the third argument, `delCount`, to remove `0` elements.
- Omit the fourth argument, `elements`, in order to not add any new 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 ```js
const names = ['alpha', 'bravo', 'charlie']; 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' ] const namesNoBravo = shank(names, 1, 1); // [ 'alpha', 'charlie' ]
console.log(names); // ['alpha', 'bravo', 'charlie'] console.log(names); // ['alpha', 'bravo', 'charlie']
``` ```

View File

@ -12,5 +12,6 @@ const show = (...el) => [...el].forEach(e => (e.style.display = ''));
``` ```
```js ```js
show(...document.querySelectorAll('img')); // Shows all <img> elements on the page show(...document.querySelectorAll('img'));
``` // Shows all <img> elements on the page
```

View File

@ -5,7 +5,8 @@ tags: array,math,beginner
Returns an array of elements that appear in both arrays. 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 ```js
const similarity = (arr, values) => arr.filter(v => values.includes(v)); const similarity = (arr, values) => arr.filter(v => values.includes(v));

View File

@ -5,7 +5,7 @@ tags: function,promise,intermediate
Delays the execution of an asynchronous function. 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 ```js
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms)); const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));

View File

@ -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. Smoothly scrolls the element on which it's called into the visible area of the browser window.
- Use `.scrollIntoView` method to scroll the element. - Use `Element.scrollIntoView()` to scroll the element.
- Pass `{ behavior: 'smooth' }` to `.scrollIntoView` so it scrolls smoothly. - Use `{ behavior: 'smooth' }` to scroll smoothly.
```js ```js
const smoothScroll = element => const smoothScroll = element =>
@ -17,5 +17,6 @@ const smoothScroll = element =>
```js ```js
smoothScroll('#fooBar'); // scrolls smoothly to the element with the id fooBar 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
``` ```

View File

@ -5,10 +5,12 @@ tags: string,beginner
Alphabetically sorts the characters in a string. 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 ```js
const sortCharactersInString = str => [...str].sort((a, b) => a.localeCompare(b)).join(''); const sortCharactersInString = str =>
[...str].sort((a, b) => a.localeCompare(b)).join('');
``` ```
```js ```js

View File

@ -3,9 +3,9 @@ title: sortedIndex
tags: array,math,intermediate 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. - Use `Array.prototype.findIndex()` to find the appropriate index where the element should be inserted.
```js ```js

View File

@ -3,16 +3,18 @@ title: sortedIndexBy
tags: array,math,intermediate 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`. - Use `Array.prototype.findIndex()` to find the appropriate index where the element should be inserted, based on the iterator function `fn`.
```js ```js
const sortedIndexBy = (arr, n, fn) => { const sortedIndexBy = (arr, n, fn) => {
const isDescending = fn(arr[0]) > fn(arr[arr.length - 1]); const isDescending = fn(arr[0]) > fn(arr[arr.length - 1]);
const val = fn(n); 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; return index === -1 ? arr.length : index;
}; };
``` ```

View File

@ -1,17 +1,19 @@
--- ---
title: sortedLastIndex 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. - Use `Array.prototype.reverse()` and `Array.prototype.findIndex()` to find the appropriate last index where the element should be inserted.
```js ```js
const sortedLastIndex = (arr, n) => { const sortedLastIndex = (arr, n) => {
const isDescending = arr[0] > arr[arr.length - 1]; 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; return index === -1 ? 0 : arr.length - index;
}; };
``` ```

View File

@ -1,11 +1,11 @@
--- ---
title: sortedLastIndexBy 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.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. - 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.

View File

@ -1,6 +1,6 @@
--- ---
title: splitLines title: splitLines
tags: string,beginner tags: string,regexp,beginner
--- ---
Splits a multiline string into an array of lines. Splits a multiline string into an array of lines.
@ -12,5 +12,6 @@ const splitLines = str => str.split(/\r?\n/);
``` ```
```js ```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.' , '']
``` ```

View File

@ -3,9 +3,9 @@ title: spreadOver
tags: function,intermediate 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 ```js
const spreadOver = fn => argsArr => fn(...argsArr); const spreadOver = fn => argsArr => fn(...argsArr);

View File

@ -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. 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.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.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. - 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 ```js
const stableSort = (arr, compare) => const stableSort = (arr, compare) =>

View File

@ -3,17 +3,18 @@ title: standardDeviation
tags: math,array,intermediate 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 - Use `Array.prototype.reduce()` to calculate the mean, variance and the sum of the variance of the values and determine the standard deviation.
- 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.
- You can omit the second argument to get the sample standard deviation or set it to `true` to get the population standard deviation.
```js ```js
const standardDeviation = (arr, usePopulation = false) => { const standardDeviation = (arr, usePopulation = false) => {
const mean = arr.reduce((acc, val) => acc + val, 0) / arr.length; const mean = arr.reduce((acc, val) => acc + val, 0) / arr.length;
return Math.sqrt( 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)) (arr.length - (usePopulation ? 0 : 1))
); );
}; };
@ -21,5 +22,6 @@ const standardDeviation = (arr, usePopulation = false) => {
```js ```js
standardDeviation([10, 2, 38, 23, 38, 23, 21]); // 13.284434142114991 (sample) 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)
``` ```

View File

@ -7,7 +7,8 @@ Generates all permutations of a string (contains duplicates).
- Use recursion. - Use recursion.
- For each letter in the given string, create all the partial permutations for the rest of its letters. - 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`. - 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. - ⚠️ **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('') .split('')
.reduce( .reduce(
(acc, letter, i) => (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 ```js
stringPermutations('abc'); // ['abc','acb','bac','bca','cab','cba'] stringPermutations('abc'); // ['abc', 'acb', 'bac', 'bca', 'cab', 'cba']
``` ```

View File

@ -5,7 +5,7 @@ tags: object,advanced
Serializes a JSON object containing circular references into a JSON format. 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. - 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. - ⚠️ **NOTICE:** This function finds and removes circular references, which causes circular data loss in the serialized JSON.

View File

@ -3,7 +3,7 @@ title: subSet
tags: array,intermediate 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 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. - Use `Array.prototype.every()` and `Set.prototype.has()` to check that each value in the first iterable is contained in the second one.

View File

@ -3,7 +3,7 @@ title: sum
tags: math,array,beginner 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`. - 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 ```js
sum(1, 2, 3, 4); // 10 sum(1, 2, 3, 4); // 10
sum(...[1, 2, 3, 4]); // 10 sum(...[1, 2, 3, 4]); // 10
``` ```

View File

@ -3,9 +3,10 @@ title: sumBy
tags: math,array,intermediate 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 ```js
const sumBy = (arr, fn) => const sumBy = (arr, fn) =>
@ -13,6 +14,6 @@ const sumBy = (arr, fn) =>
``` ```
```js ```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 sumBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], 'n'); // 20
``` ```

View File

@ -3,7 +3,7 @@ title: sumN
tags: math,beginner 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`. - Use the formula `(n * (n + 1)) / 2` to get the sum of all the numbers between 1 and `n`.

View File

@ -3,9 +3,10 @@ title: sumPower
tags: math,intermediate 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 second argument, `power`, to use a default power of `2`.
- Omit the third argument, `start`, to use a default starting value of `1`. - Omit the third argument, `start`, to use a default starting value of `1`.

View File

@ -3,7 +3,7 @@ title: superSet
tags: array,intermediate 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 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. - Use `Array.prototype.every()` and `Set.prototype.has()` to check that each value in the second iterable is contained in the first one.

View File

@ -5,7 +5,7 @@ tags: browser,beginner
Checks if touch events are supported. Checks if touch events are supported.
- Check if `ontouchstart` exists in `window`. - Check if `'ontouchstart'` exists in `window`.
```js ```js
const supportsTouchEvents = () => const supportsTouchEvents = () =>

View File

@ -5,7 +5,8 @@ tags: array,math,intermediate
Returns the symmetric difference between two arrays, without filtering out duplicate values. 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 ```js
const symmetricDifference = (a, b) => { const symmetricDifference = (a, b) => {

View File

@ -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. 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 ```js
const symmetricDifferenceBy = (a, b, fn) => { const symmetricDifferenceBy = (a, b, fn) => {
@ -17,5 +18,10 @@ const symmetricDifferenceBy = (a, b, fn) => {
```js ```js
symmetricDifferenceBy([2.1, 1.2], [2.3, 3.4], Math.floor); // [ 1.2, 3.4 ] 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 }]
``` ```

View File

@ -5,13 +5,13 @@ tags: array,beginner
Returns all elements in an array except for the first one. 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 ```js
const tail = arr => (arr.length > 1 ? arr.slice(1) : arr); const tail = arr => (arr.length > 1 ? arr.slice(1) : arr);
``` ```
```js ```js
tail([1, 2, 3]); // [2,3] tail([1, 2, 3]); // [2, 3]
tail([1]); // [1] tail([1]); // [1]
``` ```

View File

@ -3,7 +3,7 @@ title: take
tags: array,beginner 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. - Use `Array.prototype.slice()` to create a slice of the array with `n` elements taken from the beginning.

View File

@ -3,7 +3,7 @@ title: takeRight
tags: array,intermediate 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. - Use `Array.prototype.slice()` to create a slice of the array with `n` elements taken from the end.

View File

@ -3,9 +3,10 @@ title: takeRightWhile
tags: array,intermediate 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 ```js
const takeRightWhile = (arr, func) => const takeRightWhile = (arr, func) =>

View File

@ -3,7 +3,8 @@ title: takeWhile
tags: array,intermediate 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`. - 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()`. - Return the removed elements, using `Array.prototype.slice()`.

View File

@ -3,9 +3,9 @@ title: timeTaken
tags: function,beginner 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 ```js
const timeTaken = callback => { const timeTaken = callback => {

View File

@ -5,14 +5,17 @@ tags: string,regexp,intermediate
Converts a string to camelcase. 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 ```js
const toCamelCase = str => { const toCamelCase = str => {
let s = let s =
str && str &&
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()) .map(x => x.slice(0, 1).toUpperCase() + x.slice(1).toLowerCase())
.join(''); .join('');
return s.slice(0, 1).toLowerCase() + s.slice(1); return s.slice(0, 1).toLowerCase() + s.slice(1);
@ -21,7 +24,9 @@ const toCamelCase = str => {
```js ```js
toCamelCase('some_database_field_name'); // 'someDatabaseFieldName' 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-javascript-property'); // 'someJavascriptProperty'
toCamelCase('some-mixed_string with spaces_underscores-and-hyphens'); // 'someMixedStringWithSpacesUnderscoresAndHyphens' toCamelCase('some-mixed_string with spaces_underscores-and-hyphens');
// 'someMixedStringWithSpacesUnderscoresAndHyphens'
``` ```

View File

@ -3,19 +3,27 @@ title: toCurrency
tags: math,string,intermediate 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. - Use `Intl.NumberFormat` to enable country / currency sensitive formatting.
```js ```js
const toCurrency = (n, curr, LanguageFormat = undefined) => 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 ```js
toCurrency(123456.789, 'EUR'); // €123,456.79 | currency: Euro | currencyLangFormat: Local toCurrency(123456.789, 'EUR');
toCurrency(123456.789, 'USD', 'en-us'); // $123,456.79 | currency: US Dollar | currencyLangFormat: English (United States) // 123,456.79 | currency: Euro | currencyLangFormat: Local
toCurrency(123456.789, 'USD', 'fa'); // ۱۲۳٬۴۵۶٫۷۹ ؜$ | currency: US Dollar | currencyLangFormat: Farsi toCurrency(123456.789, 'USD', 'en-us');
toCurrency(322342436423.2435, 'JPY'); // ¥322,342,436,423 | currency: Japanese Yen | currencyLangFormat: Local // $123,456.79 | currency: US Dollar | currencyLangFormat: English (United States)
toCurrency(322342436423.2435, 'JPY', 'fi'); // 322 342 436 423 ¥ | currency: Japanese Yen | currencyLangFormat: Finnish 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
``` ```

View File

@ -5,7 +5,7 @@ tags: math,beginner
Converts a number to a decimal mark formatted string. 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 ```js
const toDecimalMark = num => num.toLocaleString('en-US'); const toDecimalMark = num => num.toLocaleString('en-US');

View File

@ -13,5 +13,5 @@ const toHSLArray = hslStr => hslStr.match(/\d+/g).map(Number);
``` ```
```js ```js
toHSLArray('hsl(50,10%,10%)'); // [50, 10, 10] toHSLArray('hsl(50, 10%, 10%)'); // [50, 10, 10]
``` ```

View File

@ -17,5 +17,5 @@ const toHSLObject = hslStr => {
``` ```
```js ```js
toHSLObject('hsl(50,10%,10%)'); // { hue: 50, saturation: 10, lightness: 10 } toHSLObject('hsl(50, 10%, 10%)'); // { hue: 50, saturation: 10, lightness: 10 }
``` ```

View File

@ -3,9 +3,9 @@ title: toHash
tags: array,intermediate 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 ```js
const toHash = (object, key) => 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([4, 3, 2, 1]); // { 0: 4, 1: 3, 2: 2, 3: 1 }
toHash([{ a: 'label' }], 'a'); // { label: { a: 'label' } } toHash([{ a: 'label' }], 'a'); // { label: { a: 'label' } }
// A more in depth example: // 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] }]; 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( managers.forEach(
manager => manager =>
(manager.employees = manager.employees.map(function(id) { (manager.employees = manager.employees.map(function(id) {
return this[id]; return this[id];
}, toHash(users, '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'} ] } ]
``` ```

View File

@ -1,13 +1,13 @@
--- ---
title: toISOStringWithTimezone 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`. - 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()`. - 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. - Use `pad()` and the built-in methods in the `Date` prototype to build the ISO 8601 string with timezone offset.
```js ```js
const toISOStringWithTimezone = date => { const toISOStringWithTimezone = date => {

View File

@ -5,7 +5,8 @@ tags: string,regexp,intermediate
Converts a string to kebab case. 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 ```js
const toKebabCase = str => const toKebabCase = str =>
@ -19,7 +20,9 @@ const toKebabCase = str =>
```js ```js
toKebabCase('camelCase'); // 'camel-case' toKebabCase('camelCase'); // 'camel-case'
toKebabCase('some text'); // 'some-text' 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('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'
``` ```

View File

@ -3,9 +3,10 @@ title: toPairs
tags: object,array,intermediate 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. - If `Symbol.iterator` is not defined for `obj`, use `Object.entries()` instead.
```js ```js
@ -16,8 +17,8 @@ const toPairs = obj =>
``` ```
```js ```js
toPairs({ a: 1, b: 2 }); // [ ['a', 1], ['b', 2] ] toPairs({ a: 1, b: 2 }); // [['a', 1], ['b', 2]]
toPairs([2, 4, 8]); // [ [0, 2], [1, 4], [2, 8] ] toPairs([2, 4, 8]); // [[0, 2], [1, 4], [2, 8]]
toPairs('shy'); // [ ['0', 's'], ['1', 'h'], ['2', 'y'] ] toPairs('shy'); // [['0', 's'], ['1', 'h'], ['2', 'y']]
toPairs(new Set(['a', 'b', 'c', 'a'])); // [ ['a', 'a'], ['b', 'b'], ['c', 'c'] ] toPairs(new Set(['a', 'b', 'c', 'a'])); // [['a', 'a'], ['b', 'b'], ['c', 'c']]
``` ```

View File

@ -5,7 +5,7 @@ tags: browser,beginner
Toggles a class for an HTML element. 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 ```js
const toggleClass = (el, className) => el.classList.toggle(className); const toggleClass = (el, className) => el.classList.toggle(className);

View File

@ -5,7 +5,8 @@ tags: date,intermediate
Results in a string representation of tomorrow's date. 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. - Use `Date.prototype.toISOString()` to return a string in `yyyy-mm-dd` format.
```js ```js