Update snippet descriptions

This commit is contained in:
Isabelle Viktoria Maciohsek
2020-10-20 23:02:01 +03:00
parent 52880f08ee
commit caa67e2a49
63 changed files with 175 additions and 126 deletions

View File

@ -15,5 +15,6 @@ const JSONToFile = (obj, filename) =>
``` ```
```js ```js
JSONToFile({ test: 'is passed' }, 'testJsonFile'); // writes the object to 'testJsonFile.json' JSONToFile({ test: 'is passed' }, 'testJsonFile');
// writes the object to 'testJsonFile.json'
``` ```

View File

@ -24,6 +24,13 @@ const JSONtoCSV = (arr, columns, delimiter = ',') =>
``` ```
```js ```js
JSONtoCSV([{ a: 1, b: 2 }, { a: 3, b: 4, c: 5 }, { a: 6 }, { b: 7 }], ['a', 'b']); // 'a,b\n"1","2"\n"3","4"\n"6",""\n"","7"' JSONtoCSV(
JSONtoCSV([{ a: 1, b: 2 }, { a: 3, b: 4, c: 5 }, { a: 6 }, { b: 7 }], ['a', 'b'], ';'); // 'a;b\n"1";"2"\n"3";"4"\n"6";""\n"";"7"' [{ a: 1, b: 2 }, { a: 3, b: 4, c: 5 }, { a: 6 }, { b: 7 }],
['a', 'b']
); // 'a,b\n"1","2"\n"3","4"\n"6",""\n"","7"'
JSONtoCSV(
[{ a: 1, b: 2 }, { a: 3, b: 4, c: 5 }, { a: 6 }, { b: 7 }],
['a', 'b'],
';'
); // 'a;b\n"1";"2"\n"3";"4"\n"6";""\n"";"7"'
``` ```

View File

@ -3,7 +3,7 @@ title: includesAll
tags: array,beginner tags: array,beginner
--- ---
Returns `true` if all the elements in `values` are included in `arr`, `false` otherwise. Checks if all the elements in `values` are included in `arr`.
- Use `Array.prototype.every()` and `Array.prototype.includes()` to check if all elements of `values` are included in `arr`. - Use `Array.prototype.every()` and `Array.prototype.includes()` to check if all elements of `values` are included in `arr`.

View File

@ -3,7 +3,7 @@ title: includesAny
tags: array,beginner tags: array,beginner
--- ---
Returns `true` if at least one element of values is included in arr , `false` otherwise. Checks if at least one element of `values` is included in `arr`.
- Use `Array.prototype.some()` and `Array.prototype.includes()` to check if at least one element of `values` is included in `arr`. - Use `Array.prototype.some()` and `Array.prototype.includes()` to check if at least one element of `values` is included in `arr`.

View File

@ -9,7 +9,8 @@ Indents each line in the provided string.
- Omit the third parameter, `indent`, to use a default indentation character of `' '`. - Omit the third parameter, `indent`, to use a default indentation character of `' '`.
```js ```js
const indentString = (str, count, indent = ' ') => str.replace(/^/gm, indent.repeat(count)); const indentString = (str, count, indent = ' ') =>
str.replace(/^/gm, indent.repeat(count));
``` ```
```js ```js

View File

@ -3,14 +3,14 @@ title: indexOfAll
tags: array,intermediate tags: array,intermediate
--- ---
Returns all indices of `val` in an array. Returns all indexes of `val` in an array.
If `val` never occurs, returns `[]`. If `val` never occurs, returns an empty array.
- Use `Array.prototype.reduce()` to loop over elements and store indices for matching elements. - Use `Array.prototype.reduce()` to loop over elements and store indexes for matching elements.
- Return the array of indices.
```js ```js
const indexOfAll = (arr, val) => arr.reduce((acc, el, i) => (el === val ? [...acc, i] : acc), []); const indexOfAll = (arr, val) =>
arr.reduce((acc, el, i) => (el === val ? [...acc, i] : acc), []);
``` ```
```js ```js

View File

@ -5,12 +5,12 @@ tags: array,beginner
Returns all the elements of an array except the last one. Returns all the elements of an array except the last one.
- Use `arr.slice(0,-1)` to return all but the last element of the array. - Use `Array.prototype.slice(0,-1)` to return all but the last element of the array.
```js ```js
const initial = arr => arr.slice(0, -1); const initial = arr => arr.slice(0, -1);
``` ```
```js ```js
initial([1, 2, 3]); // [1,2] initial([1, 2, 3]); // [1, 2]
``` ```

View File

@ -5,8 +5,9 @@ tags: array,intermediate
Initializes a 2D array of given width and height and value. Initializes a 2D array of given width and height and value.
- Use `Array.prototype.map()` to generate h rows where each is a new array of size w initialize with value. - Use `Array.from()` and `Array.prototype.map()` to generate `h` rows where each is a new array of size `w`.
- If the value is not provided, default to `null`. - Use `Array.prototype.fill()` to initialize all items with value `val`.
- Omit the last argument, `val`, to use a default value of `null`.
```js ```js
const initialize2DArray = (w, h, val = null) => const initialize2DArray = (w, h, val = null) =>
@ -14,5 +15,5 @@ const initialize2DArray = (w, h, val = null) =>
``` ```
```js ```js
initialize2DArray(2, 2, 0); // [[0,0], [0,0]] initialize2DArray(2, 2, 0); // [[0, 0], [0, 0]]
``` ```

View File

@ -1,13 +1,14 @@
--- ---
title: initializeArrayWithRange title: initializeArrayWithRange
tags: array,math,intermediate tags: array,intermediate
--- ---
Initializes an array containing the numbers in the specified range where `start` and `end` are inclusive with their common difference `step`. Initializes an array containing the numbers in the specified range where `start` and `end` are inclusive with their common difference `step`.
- Use `Array.from()` to create an array of the desired length, `(end - start + 1)/step`, and a map function to fill it with the desired values in the given range. - Use `Array.from()` to create an array of the desired length.
- You can omit `start` to use a default value of `0`. - Use `(end - start + 1)/step` and a map function to fill the array with the desired values in the given range.
- You can omit `step` to use a default value of `1`. - Omit the second argument, `start`, to use a default value of `0`.
- Omit the last argument, `step`, to use a default value of `1`.
```js ```js
const initializeArrayWithRange = (end, start = 0, step = 1) => const initializeArrayWithRange = (end, start = 0, step = 1) =>
@ -15,7 +16,7 @@ const initializeArrayWithRange = (end, start = 0, step = 1) =>
``` ```
```js ```js
initializeArrayWithRange(5); // [0,1,2,3,4,5] initializeArrayWithRange(5); // [0, 1, 2, 3, 4, 5]
initializeArrayWithRange(7, 3); // [3,4,5,6,7] initializeArrayWithRange(7, 3); // [3, 4, 5, 6, 7]
initializeArrayWithRange(9, 0, 2); // [0,2,4,6,8] initializeArrayWithRange(9, 0, 2); // [0, 2, 4, 6, 8]
``` ```

View File

@ -1,13 +1,13 @@
--- ---
title: initializeArrayWithRangeRight title: initializeArrayWithRangeRight
tags: array,math,intermediate tags: array,intermediate
--- ---
Initializes an array containing the numbers in the specified range (in reverse) where `start` and `end` are inclusive with their common difference `step`. Initializes an array containing the numbers in the specified range (in reverse) where `start` and `end` are inclusive with their common difference `step`.
- Use `Array.from(Math.ceil((end+1-start)/step))` to create an array of the desired length(the amounts of elements is equal to `(end-start)/step` or `(end+1-start)/step` for inclusive end), `Array.prototype.map()` to fill with the desired values in a range. - Use `Array.from(Math.ceil((end+1-start)/step))` to create an array of the desired length(the amounts of elements is equal to `(end-start)/step` or `(end+1-start)/step` for inclusive end), `Array.prototype.map()` to fill with the desired values in a range.
- You can omit `start` to use a default value of `0`. - Omit the second argument, `start`, to use a default value of `0`.
- You can omit `step` to use a default value of `1`. - Omit the last argument, `step`, to use a default value of `1`.
```js ```js
const initializeArrayWithRangeRight = (end, start = 0, step = 1) => const initializeArrayWithRangeRight = (end, start = 0, step = 1) =>
@ -17,7 +17,7 @@ const initializeArrayWithRangeRight = (end, start = 0, step = 1) =>
``` ```
```js ```js
initializeArrayWithRangeRight(5); // [5,4,3,2,1,0] initializeArrayWithRangeRight(5); // [5, 4, 3, 2, 1, 0]
initializeArrayWithRangeRight(7, 3); // [7,6,5,4,3] initializeArrayWithRangeRight(7, 3); // [7, 6, 5, 4, 3]
initializeArrayWithRangeRight(9, 0, 2); // [8,6,4,2,0] initializeArrayWithRangeRight(9, 0, 2); // [8, 6, 4, 2, 0]
``` ```

View File

@ -1,15 +1,16 @@
--- ---
title: initializeArrayWithValues title: initializeArrayWithValues
tags: array,math,intermediate tags: array,intermediate
--- ---
Initializes and fills an array with the specified values. Initializes and fills an array with the specified values.
- Use `Array(n)` to create an array of the desired length, `fill(v)` to fill it with the desired values. - Use `Array.from()` to create an array of the desired length, `Array.prototype.fill()` to fill it with the desired values.
- You can omit `val` to use a default value of `0`. - Omit the last argument, `val`, to use a default value of `0`.
```js ```js
const initializeArrayWithValues = (n, val = 0) => Array(n).fill(val); const initializeArrayWithValues = (n, val = 0) =>
Array.from({ length: n }).fill(val);
``` ```
```js ```js

View File

@ -6,7 +6,7 @@ tags: array,recursion,intermediate
Create a n-dimensional array with given value. Create a n-dimensional array with given value.
- Use recursion. - Use recursion.
- Use `Array.prototype.map()` to generate rows where each is a new array initialized using `initializeNDArray`. - Use `Array.from()`, `Array.prototype.map()` to generate rows where each is a new array initialized using `initializeNDArray()`.
```js ```js
const initializeNDArray = (val, ...args) => const initializeNDArray = (val, ...args) =>
@ -16,6 +16,6 @@ const initializeNDArray = (val, ...args) =>
``` ```
```js ```js
initializeNDArray(1, 3); // [1,1,1] initializeNDArray(1, 3); // [1, 1, 1]
initializeNDArray(5, 2, 2, 2); // [[[5,5],[5,5]],[[5,5],[5,5]]] initializeNDArray(5, 2, 2, 2); // [[[5, 5], [5, 5]], [[5, 5], [5, 5]]]
``` ```

View File

@ -3,10 +3,11 @@ title: injectCSS
tags: browser,css,intermediate tags: browser,css,intermediate
--- ---
Injects the given css code into the current document Injects the given CSS code into the current document
- Use `Document.createElement()` to create a new `style` element and set its type to `text/css`. - Use `Document.createElement()` to create a new `style` element and set its type to `text/css`.
- Use `Element.innerText` to set the value to the given css string, `Document.head` and `Element.appendChild()` to append the new element to the document head. - Use `Element.innerText` to set the value to the given CSS string.
- Use `Document.head` and `Element.appendChild()` to append the new element to the document head.
- Return the newly created `style` element. - Return the newly created `style` element.
```js ```js
@ -20,5 +21,6 @@ const injectCSS = css => {
``` ```
```js ```js
injectCSS('body { background-color: #000 }'); // '<style type="text/css">body { background-color: #000 }</style>' injectCSS('body { background-color: #000 }');
// '<style type="text/css">body { background-color: #000 }</style>'
``` ```

View File

@ -5,10 +5,11 @@ tags: browser,beginner
Inserts an HTML string after the end of the specified element. Inserts an HTML string after the end of the specified element.
- Use `el.insertAdjacentHTML()` with a position of `'afterend'` to parse `htmlString` and insert it after the end of `el`. - Use `Element.insertAdjacentHTML()` with a position of `'afterend'` to parse `htmlString` and insert it after the end of `el`.
```js ```js
const insertAfter = (el, htmlString) => el.insertAdjacentHTML('afterend', htmlString); const insertAfter = (el, htmlString) =>
el.insertAdjacentHTML('afterend', htmlString);
``` ```
```js ```js

View File

@ -3,7 +3,7 @@ title: insertAt
tags: array,intermediate tags: array,intermediate
--- ---
Mutates the original array to insert the given values at the specified index. Mutates the original array to insert the given values after the specified index.
- Use `Array.prototype.splice()` with an appropriate index and a delete count of `0`, spreading the given values to be inserted. - Use `Array.prototype.splice()` with an appropriate index and a delete count of `0`, spreading the given values to be inserted.

View File

@ -5,10 +5,11 @@ tags: browser,beginner
Inserts an HTML string before the start of the specified element. Inserts an HTML string before the start of the specified element.
- Use `el.insertAdjacentHTML()` with a position of `'beforebegin'` to parse `htmlString` and insert it before the start of `el`. - Use `Element.insertAdjacentHTML()` with a position of `'beforebegin'` to parse `htmlString` and insert it before the start of `el`.
```js ```js
const insertBefore = (el, htmlString) => el.insertAdjacentHTML('beforebegin', htmlString); const insertBefore = (el, htmlString) =>
el.insertAdjacentHTML('beforebegin', htmlString);
``` ```
```js ```js

View File

@ -1,9 +1,9 @@
--- ---
title: intersection title: intersection
tags: array,math,intermediate tags: array,intermediate
--- ---
Returns the elements that exist in both arrays. Returns the elements that exist in both arrays, filtering duplicate values.
- Create a `Set` from `b`, then use `Array.prototype.filter()` on `a` to only keep values contained in `b`. - Create a `Set` from `b`, then use `Array.prototype.filter()` on `a` to only keep values contained in `b`.

View File

@ -5,7 +5,8 @@ tags: array,intermediate
Returns the elements that exist in both arrays, after applying the provided function to each array element of both. Returns the elements that exist in both arrays, after applying the provided function to each array element of both.
- Create a `Set` by applying `fn` to all elements in `b`, then use `Array.prototype.filter()` on `a` to only keep elements, which produce values contained in `b` when `fn` is applied to them. - Create a `Set` by applying `fn` to all elements in `b`.
- Use `Array.prototype.filter()` on `a` to only keep elements, which produce values contained in `b` when `fn` is applied to them.
```js ```js
const intersectionBy = (a, b, fn) => { const intersectionBy = (a, b, fn) => {
@ -16,5 +17,9 @@ const intersectionBy = (a, b, fn) => {
```js ```js
intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor); // [2.1] intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor); // [2.1]
intersectionBy([{ title: 'Apple' }, { title: 'Orange' }], [{ title: 'Orange' }, { title: 'Melon' }], x => x.title) // [{ title: 'Orange' }] intersectionBy(
[{ title: 'Apple' }, { title: 'Orange' }],
[{ title: 'Orange' }, { title: 'Melon' }],
x => x.title
); // [{ title: 'Orange' }]
``` ```

View File

@ -8,9 +8,14 @@ Returns the elements that exist in both arrays, using a provided comparator func
- Use `Array.prototype.filter()` and `Array.prototype.findIndex()` in combination with the provided comparator to determine intersecting values. - Use `Array.prototype.filter()` and `Array.prototype.findIndex()` in combination with the provided comparator to determine intersecting values.
```js ```js
const intersectionWith = (a, b, comp) => a.filter(x => b.findIndex(y => comp(x, y)) !== -1); const intersectionWith = (a, b, comp) =>
a.filter(x => b.findIndex(y => comp(x, y)) !== -1);
``` ```
```js ```js
intersectionWith([1, 1.2, 1.5, 3, 0], [1.9, 3, 0, 3.9], (a, b) => Math.round(a) === Math.round(b)); // [1.5, 3, 0] intersectionWith(
[1, 1.2, 1.5, 3, 0],
[1.9, 3, 0, 3.9],
(a, b) => Math.round(a) === Math.round(b)
); // [1.5, 3, 0]
``` ```

View File

@ -1,12 +1,13 @@
--- ---
title: invertKeyValues title: invertKeyValues
tags: object,intermediate tags: object,advanced
--- ---
Inverts the key-value pairs of an object, without mutating it. The corresponding inverted value of each inverted key is an array of keys responsible for generating the inverted value. If a function is supplied, it is applied to each inverted key. Inverts the key-value pairs of an object, without mutating it.
- Use `Object.keys()` and `Array.prototype.reduce()` to invert the key-value pairs of an object and apply the function provided (if any). - Use `Object.keys()` and `Array.prototype.reduce()` to invert the key-value pairs of an object and apply the function provided (if any).
- Omit the second argument, `fn`, to get the inverted keys without applying a function to them. - Omit the second argument, `fn`, to get the inverted keys without applying a function to them.
- The corresponding inverted value of each inverted key is an array of keys responsible for generating the inverted value. If a function is supplied, it is applied to each inverted key.
```js ```js
const invertKeyValues = (obj, fn) => const invertKeyValues = (obj, fn) =>
@ -20,5 +21,6 @@ const invertKeyValues = (obj, fn) =>
```js ```js
invertKeyValues({ a: 1, b: 2, c: 1 }); // { 1: [ 'a', 'c' ], 2: [ 'b' ] } invertKeyValues({ a: 1, b: 2, c: 1 }); // { 1: [ 'a', 'c' ], 2: [ 'b' ] }
invertKeyValues({ a: 1, b: 2, c: 1 }, value => 'group' + value); // { group1: [ 'a', 'c' ], group2: [ 'b' ] } invertKeyValues({ a: 1, b: 2, c: 1 }, value => 'group' + value);
// { group1: [ 'a', 'c' ], group2: [ 'b' ] }
``` ```

View File

@ -1,11 +1,12 @@
--- ---
title: is title: is
tags: type,array,regexp,beginner tags: type,array,intermediate
--- ---
Checks if the provided value is of the specified type. Checks if the provided value is of the specified type.
- Ensure the value is not `undefined` or `null` using `Array.prototype.includes()`, and compare the `constructor` property on the value with `type` to check if the provided value is of the specified `type`. - Ensure the value is not `undefined` or `null` using `Array.prototype.includes()`.
- Compare the `constructor` property on the value with `type` to check if the provided value is of the specified `type`.
```js ```js
const is = (type, val) => ![, null].includes(val) && val.constructor === type; const is = (type, val) => ![, null].includes(val) && val.constructor === type;

View File

@ -1,11 +1,11 @@
--- ---
title: isAbsoluteURL title: isAbsoluteURL
tags: string,browser,intermediate tags: string,browser,regexp,intermediate
--- ---
Returns `true` if the given string is an absolute URL, `false` otherwise. Checks if the given string is an absolute URL.
- Use a regular expression to test if the string is an absolute URL. - Use `RegExp.prototype.test()` to test if the string is an absolute URL.
```js ```js
const isAbsoluteURL = str => /^[a-z][a-z0-9+.-]*:/.test(str); const isAbsoluteURL = str => /^[a-z][a-z0-9+.-]*:/.test(str);

View File

@ -3,7 +3,7 @@ title: isAfterDate
tags: date,beginner tags: date,beginner
--- ---
Check if a date is after another date. Checks if a date is after another date.
- Use the greater than operator (`>`) to check if the first date comes after the second one. - Use the greater than operator (`>`) to check if the first date comes after the second one.

View File

@ -5,7 +5,7 @@ tags: string,regexp,beginner
Checks if a string contains only alphanumeric characters. Checks if a string contains only alphanumeric characters.
- Use `RegExp.prototype.test()` to check if input string matches against alphanumeric regex pattern. - Use `RegExp.prototype.test()` to check if the input string matches against the alphanumeric regexp pattern.
```js ```js
const isAlphaNumeric = str => /^[a-z0-9]+$/gi.test(str); const isAlphaNumeric = str => /^[a-z0-9]+$/gi.test(str);

View File

@ -5,7 +5,8 @@ tags: string,regexp,intermediate
Checks if a string is an anagram of another string (case-insensitive, ignores spaces, punctuation and special characters). Checks if a string is an anagram of another string (case-insensitive, ignores spaces, punctuation and special characters).
- Use `String.prototype.toLowerCase()`, `String.prototype.replace()` with an appropriate regular expression to remove unnecessary characters, `String.prototype.split('')`, `Array.prototype.sort()` and `Array.prototype.join('')` on both strings to normalize them, then check if their normalized forms are equal. - Use `String.prototype.toLowerCase()` and `String.prototype.replace()` with an appropriate regular expression to remove unnecessary characters.
- Use `String.prototype.split('')`, `Array.prototype.sort()` and `Array.prototype.join('')` on both strings to normalize them, then check if their normalized forms are equal.
```js ```js
const isAnagram = (str1, str2) => { const isAnagram = (str1, str2) => {

View File

@ -8,7 +8,8 @@ Checks if the provided argument is array-like (i.e. is iterable).
- Check if the provided argument is not `null` and that its `Symbol.iterator` property is a function. - Check if the provided argument is not `null` and that its `Symbol.iterator` property is a function.
```js ```js
const isArrayLike = obj => obj != null && typeof obj[Symbol.iterator] === 'function'; const isArrayLike = obj =>
obj != null && typeof obj[Symbol.iterator] === 'function';
``` ```
```js ```js

View File

@ -3,7 +3,7 @@ title: isBeforeDate
tags: date,beginner tags: date,beginner
--- ---
Check if a date is before another date. Checks if a date is before another date.
- Use the less than operator (`<`) to check if the first date comes before the second one. - Use the less than operator (`<`) to check if the first date comes before the second one.

View File

@ -3,15 +3,24 @@ title: isBetweenDates
tags: date,beginner tags: date,beginner
--- ---
Check if a date is between two other dates. Checks if a date is between two other dates.
- Use the greater than (`>`) and less than (`<`) operators to check if `date` is between `dateStart` and `dateEnd`. - Use the greater than (`>`) and less than (`<`) operators to check if `date` is between `dateStart` and `dateEnd`.
```js ```js
const isBetweenDates = (dateStart, dateEnd, date) => date > dateStart && date < dateEnd; const isBetweenDates = (dateStart, dateEnd, date) =>
date > dateStart && date < dateEnd;
``` ```
```js ```js
isBetweenDates(new Date(2010, 11, 20), new Date(2010, 11, 30), new Date(2010, 11, 19)); // false isBetweenDates(
isBetweenDates(new Date(2010, 11, 20), new Date(2010, 11, 30), new Date(2010, 11, 25)); // true new Date(2010, 11, 20),
new Date(2010, 11, 30),
new Date(2010, 11, 19)
); // false
isBetweenDates(
new Date(2010, 11, 20),
new Date(2010, 11, 30),
new Date(2010, 11, 25)
); // true
``` ```

View File

@ -1,6 +1,6 @@
--- ---
title: isBrowser title: isBrowser
tags: browser,intermediate tags: browser,node,intermediate
--- ---
Determines if the current runtime environment is a browser so that front-end modules can run on the server (Node) without throwing errors. Determines if the current runtime environment is a browser so that front-end modules can run on the server (Node) without throwing errors.

View File

@ -3,9 +3,9 @@ title: isBrowserTabFocused
tags: browser,beginner tags: browser,beginner
--- ---
Returns `true` if the browser tab of the page is focused, `false` otherwise. Checks if the browser tab of the page is focused.
- Use the `Document.hidden` property, introduced by the Page Visibility API to check if the browser tab of the page is visible or hidden. - Use the `Document.hidden` property, introduced by the [Page Visibility API](https://developer.mozilla.org/en-US/docs/Web/API/Page_Visibility_API) to check if the browser tab of the page is visible or hidden.
```js ```js
const isBrowserTabFocused = () => !document.hidden; const isBrowserTabFocused = () => !document.hidden;

View File

@ -3,10 +3,11 @@ title: isContainedIn
tags: array,intermediate tags: array,intermediate
--- ---
Returns `true` if the elements of the first array are contained in the second one regardless of order, `false` otherwise. Checks if the elements of the first array are contained in the second one regardless of order.
- Use a `for...of` loop over a `Set` created from the first array. - Use a `for...of` loop over a `Set` created from the first array.
- Use `Array.prototype.some()` to check if all distinct values are contained in the second array, use `Array.prototype.filter()` to compare the number of occurrences of each distinct value in both arrays. - Use `Array.prototype.some()` to check if all distinct values are contained in the second array.
- Use `Array.prototype.filter()` to compare the number of occurrences of each distinct value in both arrays.
- Return `false` if the count of any element is greater in the first array than the second one, `true` otherwise. - Return `false` if the count of any element is greater in the first array than the second one, `true` otherwise.
```js ```js

View File

@ -3,13 +3,13 @@ title: isDateValid
tags: date,intermediate tags: date,intermediate
--- ---
Returns `true` if a valid date object can be created from the given values, `false` otherwise. Checks if a valid date object can be created from the given values.
- Use the spread operator (`...`) to pass the array of arguments to the `Date` constructor. - Use the spread operator (`...`) to pass the array of arguments to the `Date` constructor.
- Use `Date.prototype.valueOf()` and `Number.isNaN()` to check if a valid `Date` object can be created from the given values. - Use `Date.prototype.valueOf()` and `Number.isNaN()` to check if a valid `Date` object can be created from the given values.
```js ```js
const isDateValid = (...val) => !isNaN(new Date(...val).valueOf()); const isDateValid = (...val) => !Number.isNaN(new Date(...val).valueOf());
``` ```
```js ```js

View File

@ -3,7 +3,7 @@ title: isDeepFrozen
tags: object,recursion,intermediate tags: object,recursion,intermediate
--- ---
Checks if an object is deeply frozen Checks if an object is deeply frozen.
- Use recursion. - Use recursion.
- Use `Object.isFrozen()` on the given object. - Use `Object.isFrozen()` on the given object.

View File

@ -5,7 +5,8 @@ tags: node,type,intermediate
Checks if the given argument is a duplex (readable and writable) stream. Checks if the given argument is a duplex (readable and writable) stream.
- Check if the value is different from `null`, use `typeof` to check if a value is of type `object` and the `pipe` property is of type `function`. - Check if the value is different from `null`.
- Use `typeof` to check if a value is of type `object` and the `pipe` property is of type `function`.
- Additionally check if the `typeof` the `_read`, `_write` and `_readableState`, `_writableState` properties are `function` and `object` respectively. - Additionally check if the `typeof` the `_read`, `_write` and `_readableState`, `_writableState` properties are `function` and `object` respectively.
```js ```js

View File

@ -13,6 +13,6 @@ const hasDuplicates = arr => new Set(arr).size !== arr.length;
``` ```
```js ```js
hasDuplicates([0,1,1,2]); // true hasDuplicates([0, 1, 1, 2]); // true
hasDuplicates([0,1,2,3,]); // false hasDuplicates([0, 1, 2, 3]); // false
``` ```

View File

@ -3,7 +3,7 @@ title: isEmpty
tags: type,array,object,string,beginner tags: type,array,object,string,beginner
--- ---
Returns true if the a value is an empty object, collection, has no enumerable properties or is any type that is not considered a collection. Checks if the a value is an empty object/collection, has no enumerable properties or is any type that is not considered a collection.
- Check if the provided value is `null` or if its `length` is equal to `0`. - Check if the provided value is `null` or if its `length` is equal to `0`.

View File

@ -3,7 +3,7 @@ title: isEven
tags: math,beginner tags: math,beginner
--- ---
Returns `true` if the given number is even, `false` otherwise. Checks if the given number is even.
- Checks whether a number is odd or even using the modulo (`%`) operator. - Checks whether a number is odd or even using the modulo (`%`) operator.
- Returns `true` if the number is even, `false` if the number is odd. - Returns `true` if the number is even, `false` if the number is odd.

View File

@ -3,9 +3,10 @@ title: isLeapYear
tags: date,beginner tags: date,beginner
--- ---
Returns `true` if the given `year` is a leap year, `false` otherwise. Checks if the given `year` is a leap year.
- Use `new Date()`, setting the date to February 29th of the given `year` and use `Date.prototype.getMonth()` to check if the month is equal to `1`. - Use `new Date()`, setting the date to February 29th of the given `year`.
- Use `Date.prototype.getMonth()` to check if the month is equal to `1`.
```js ```js
const isLeapYear = year => new Date(year, 1, 29).getMonth() === 1; const isLeapYear = year => new Date(year, 1, 29).getMonth() === 1;

View File

@ -1,11 +1,11 @@
--- ---
title: isNegativeZero title: isNegativeZero
tags: math,beginner tags: math,intermediate
--- ---
Checks if the given value is equal to negative zero (`-0`). Checks if the given value is equal to negative zero (`-0`).
- Checks whether a passed value is equal to `0` and if `1` divided by the value equals `-Infinity`. - Check whether a passed value is equal to `0` and if `1` divided by the value equals `-Infinity`.
```js ```js
const isNegativeZero = val => val === 0 && 1 / val === -Infinity; const isNegativeZero = val => val === 0 && 1 / val === -Infinity;

View File

@ -3,7 +3,7 @@ title: isNil
tags: type,beginner tags: type,beginner
--- ---
Returns `true` if the specified value is `null` or `undefined`, `false` otherwise. Checks if the specified value is `null` or `undefined`.
- Use the strict equality operator to check if the value of `val` is equal to `null` or `undefined`. - Use the strict equality operator to check if the value of `val` is equal to `null` or `undefined`.

View File

@ -1,6 +1,6 @@
--- ---
title: isNode title: isNode
tags: node,intermediate tags: node,browser,intermediate
--- ---
Determines if the current runtime environment is Node.js. Determines if the current runtime environment is Node.js.

View File

@ -3,7 +3,7 @@ title: isNull
tags: type,beginner tags: type,beginner
--- ---
Returns `true` if the specified value is `null`, `false` otherwise. Checks if the specified value is `null`.
- Use the strict equality operator to check if the value of `val` is equal to `null`. - Use the strict equality operator to check if the value of `val` is equal to `null`.

View File

@ -5,7 +5,7 @@ tags: type,object,beginner
Returns a boolean determining if the passed value is an object or not. Returns a boolean determining if the passed value is an object or not.
- Uses the `Object` constructor to create an object wrapper for the given value. - Uses the `Object` constructor to create an object wrapper for the given value.
- If the value is `null` or `undefined`, create and return an empty object. - If the value is `null` or `undefined`, create and return an empty object.
- Οtherwise, return an object of a type that corresponds to the given value. - Οtherwise, return an object of a type that corresponds to the given value.

View File

@ -3,10 +3,10 @@ title: isOdd
tags: math,beginner tags: math,beginner
--- ---
Returns `true` if the given number is odd, `false` otherwise. Checks if the given number is odd.
- Checks whether a number is odd or even using the modulo (`%`) operator. - Check whether a number is odd or even using the modulo (`%`) operator.
- Returns `true` if the number is odd, `false` if the number is even. - Return `true` if the number is odd, `false` if the number is even.
```js ```js
const isOdd = num => num % 2 === 1; const isOdd = num => num % 2 === 1;

View File

@ -5,10 +5,12 @@ tags: type,object,intermediate
Checks if the provided value is an object created by the Object constructor. Checks if the provided value is an object created by the Object constructor.
- Check if the provided value is truthy, use `typeof` to check if it is an object and `Object.prototype.constructor` to make sure the constructor is equal to `Object`. - Check if the provided value is truthy.
- Use `typeof` to check if it is an object and `Object.prototype.constructor` to make sure the constructor is equal to `Object`.
```js ```js
const isPlainObject = val => !!val && typeof val === 'object' && val.constructor === Object; const isPlainObject = val =>
!!val && typeof val === 'object' && val.constructor === Object;
``` ```
```js ```js

View File

@ -3,7 +3,7 @@ title: isPowerOfTwo
tags: math,beginner tags: math,beginner
--- ---
Returns `true` if the given number is a power of `2`, `false` otherwise. Checks if the given number is a power of `2`.
- Use the bitwise binary AND operator (`&`) to determine if `n` is a power of `2`. - Use the bitwise binary AND operator (`&`) to determine if `n` is a power of `2`.
- Additionally, check that `n` is not falsy. - Additionally, check that `n` is not falsy.

View File

@ -3,7 +3,7 @@ title: isPromiseLike
tags: type,function,promise,intermediate tags: type,function,promise,intermediate
--- ---
Returns `true` if an object looks like a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise), `false` otherwise. Checks if an object looks like a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
- Check if the object is not `null`, its `typeof` matches either `object` or `function` and if it has a `.then` property, which is also a `function`. - Check if the object is not `null`, its `typeof` matches either `object` or `function` and if it has a `.then` property, which is also a `function`.

View File

@ -5,7 +5,8 @@ tags: node,type,intermediate
Checks if the given argument is a readable stream. Checks if the given argument is a readable stream.
- Check if the value is different from `null`, use `typeof` to check if the value is of type `object` and the `pipe` property is of type `function`. - Check if the value is different from `null`.
- Use `typeof` to check if the value is of type `object` and the `pipe` property is of type `function`.
- Additionally check if the `typeof` the `_read` and `_readableState` properties are `function` and `object` respectively. - Additionally check if the `typeof` the `_read` and `_readableState` properties are `function` and `object` respectively.
```js ```js

View File

@ -3,7 +3,7 @@ title: isSameDate
tags: date,beginner tags: date,beginner
--- ---
Check if a date is the same as another date. Checks if a date is the same as another date.
- Use `Date.prototype.toISOString()` and strict equality checking (`===`) to check if the first date is the same as the second one. - Use `Date.prototype.toISOString()` and strict equality checking (`===`) to check if the first date is the same as the second one.

View File

@ -3,11 +3,11 @@ title: isSorted
tags: array,intermediate tags: array,intermediate
--- ---
Returns `1` if a numeric array is sorted in ascending order, `-1` if it is sorted in descending order or `0` if it is not sorted. Checks if a numeric array is sorted.
- Calculate the ordering `direction` for the first pair of adjacent array elements. - Calculate the ordering `direction` for the first pair of adjacent array elements.
- Return `0` if the given array is empty, only has one element or the `direction` changes for any pair of adjacent array elements. - Return `0` if the given array is empty, only has one element or the `direction` changes for any pair of adjacent array elements.
- Use `Math.sign()` to covert the final value of `direction` to `-1` or `1`. - Use `Math.sign()` to covert the final value of `direction` to `-1` (descending order) or `1` (ascending order).
```js ```js
const isSorted = arr => { const isSorted = arr => {

View File

@ -5,10 +5,12 @@ tags: node,type,intermediate
Checks if the given argument is a stream. Checks if the given argument is a stream.
- Check if the value is different from `null`, use `typeof` to check if the value is of type `object` and the `pipe` property is of type `function`. - Check if the value is different from `null`.
- Use `typeof` to check if the value is of type `object` and the `pipe` property is of type `function`.
```js ```js
const isStream = val => val !== null && typeof val === 'object' && typeof val.pipe === 'function'; const isStream = val =>
val !== null && typeof val === 'object' && typeof val.pipe === 'function';
``` ```
```js ```js

View File

@ -3,7 +3,8 @@ title: isString
tags: type,string,beginner tags: type,string,beginner
--- ---
Checks if the given argument is a string. Only works for string primitives. Checks if the given argument is a string.
Only works for string primitives.
- Use `typeof` to check if a value is classified as a string primitive. - Use `typeof` to check if a value is classified as a string primitive.

View File

@ -5,7 +5,7 @@ tags: node,intermediate
Checks if the current environment is [Travis CI](https://travis-ci.org/). Checks if the current environment is [Travis CI](https://travis-ci.org/).
- Checks if the current environment has the `TRAVIS` and `CI` environment variables ([reference](https://docs.travis-ci.com/user/environment-variables/#Default-Environment-Variables)). - Check if the current environment has the `TRAVIS` and `CI` environment variables ([reference](https://docs.travis-ci.com/user/environment-variables/#Default-Environment-Variables)).
```js ```js
const isTravisCI = () => 'TRAVIS' in process.env && 'CI' in process.env; const isTravisCI = () => 'TRAVIS' in process.env && 'CI' in process.env;

View File

@ -3,7 +3,7 @@ title: isUndefined
tags: type,beginner tags: type,beginner
--- ---
Returns `true` if the specified value is `undefined`, `false` otherwise. Checks if the specified value is `undefined`.
- Use the strict equality operator to check if `val` is equal to `undefined`. - Use the strict equality operator to check if `val` is equal to `undefined`.

View File

@ -3,10 +3,10 @@ title: isWeekday
tags: date,beginner tags: date,beginner
--- ---
Results in a boolean representation of a specific date. Checks if the given date is a weekday.
- Pass the specific date object firstly. - Use `Date.prototype.getDay()` to check weekday by using a modulo operator (`%`).
- Use `Date.prototype.getDay()` to check weekday by using a modulo operator and then returning a boolean. - Omit the argument, `d`, to use the current date as default.
```js ```js
const isWeekday = (d = new Date()) => d.getDay() % 6 !== 0; const isWeekday = (d = new Date()) => d.getDay() % 6 !== 0;

View File

@ -3,15 +3,13 @@ title: isWeekend
tags: date,beginner tags: date,beginner
--- ---
Results in a boolean representation of a specific date. Checks if the given date is a weekend.
- Pass the specific date object firstly. - Use `Date.prototype.getDay()` to check weekend by using a modulo operator (`%`).
- Use `Date.prototype.getDay()` to check weekend based on the day being returned as 0 - 6 using a modulo operation then return a boolean. - Omit the argument, `d`, to use the current date as default.
```js ```js
const isWeekend = (d = new Date()) => { const isWeekend = (d = new Date()) => d.getDay() % 6 === 0;
return d.getDay() % 6 === 0;
};
``` ```
```js ```js

View File

@ -5,7 +5,8 @@ tags: node,type,intermediate
Checks if the given argument is a writable stream. Checks if the given argument is a writable stream.
- Check if the value is different from `null`, use `typeof` to check if the value is of type `object` and the `pipe` property is of type `function`. - Check if the value is different from `null`.
- Use `typeof` to check if the value is of type `object` and the `pipe` property is of type `function`.
- Additionally check if the `typeof` the `_write` and `_writableState` properties are `function` and `object` respectively. - Additionally check if the `typeof` the `_write` and `_writableState` properties are `function` and `object` respectively.
```js ```js

View File

@ -25,7 +25,7 @@ const join = (arr, separator = ',', end = separator) =>
``` ```
```js ```js
join(['pen', 'pineapple', 'apple', 'pen'], ',', '&'); // "pen,pineapple,apple&pen" join(['pen', 'pineapple', 'apple', 'pen'], ',', '&'); // 'pen,pineapple,apple&pen'
join(['pen', 'pineapple', 'apple', 'pen'], ','); // "pen,pineapple,apple,pen" join(['pen', 'pineapple', 'apple', 'pen'], ','); // 'pen,pineapple,apple,pen'
join(['pen', 'pineapple', 'apple', 'pen']); // "pen,pineapple,apple,pen" join(['pen', 'pineapple', 'apple', 'pen']); // 'pen,pineapple,apple,pen'
``` ```

View File

@ -17,10 +17,9 @@ juxt(
x => x + 1, x => x + 1,
x => x - 1, x => x - 1,
x => x * 10 x => x * 10
)(1, 2, 3); // [[2,3,4],[0,1,2],[10,20,30]] )(1, 2, 3); // [[2, 3, 4], [0, 1, 2], [10, 20, 30]]
juxt( juxt(
s => s.length, s => s.length,
s => s.split(" ").join("-") s => s.split(" ").join("-")
)("30 seconds of code"); // [[18],['30-seconds-of-code']] )("30 seconds of code"); // [[18], ['30-seconds-of-code']]
``` ```

View File

@ -5,7 +5,8 @@ tags: array,beginner
Returns the last element in an array. Returns the last element in an array.
- Check if `arr` is truthy and has a `length` property, use `arr.length - 1` to compute the index of the last element of the given array and return it, otherwise return `undefined`. - Check if `arr` is truthy and has a `length` property.
- Use `Array.prototype.length - 1` to compute the index of the last element of the given array and return it, otherwise return `undefined`.
```js ```js
const last = arr => (arr && arr.length ? arr[arr.length - 1] : undefined); const last = arr => (arr && arr.length ? arr[arr.length - 1] : undefined);

View File

@ -1,6 +1,6 @@
--- ---
title: lcm title: lcm
tags: math,recursion,beginner tags: math,recursion,intermediate
--- ---
Returns the least common multiple of two or more numbers. Returns the least common multiple of two or more numbers.

View File

@ -5,7 +5,8 @@ tags: browser,event,beginner
Adds an event listener to an element that will only run the callback the first time the event is triggered. Adds an event listener to an element that will only run the callback the first time the event is triggered.
- Use `EventTarget.addEventListener()` to add an event listener to an element, using `{ once: true }` as options to only run the given callback once. - Use `EventTarget.addEventListener()` to add an event listener to an element.
- Use `{ once: true }` as options to only run the given callback once.
```js ```js
const listenOnce = (el, evt, fn) => el.addEventListener(evt, fn, { once: true }); const listenOnce = (el, evt, fn) => el.addEventListener(evt, fn, { once: true });

View File

@ -4,10 +4,10 @@ tags: array,intermediate
--- ---
Takes any number of iterable objects or objects with a `length` property and returns the longest one. Takes any number of iterable objects or objects with a `length` property and returns the longest one.
If multiple objects have the same length, the first one will be returned.
Returns `undefined` if no arguments are provided.
- Use `Array.prototype.reduce()`, comparing the `length` of objects to find the longest one. - Use `Array.prototype.reduce()`, comparing the `length` of objects to find the longest one.
- If multiple objects have the same length, the first one will be returned.
- Returns `undefined` if no arguments are provided.
```js ```js
const longestItem = (...vals) => vals.reduce((a, x) => (x.length > a.length ? x : a)); const longestItem = (...vals) => vals.reduce((a, x) => (x.length > a.length ? x : a));