Avoid confusing prototype methods for static methods

Correct: `Array.from()` (it’s a static method)
Incorrect: `Array.join()` (doesn’t exist; it’s a prototype method)

This patch uses the common `#` syntax to denote `.prototype.`.
This commit is contained in:
Mathias Bynens
2018-09-28 15:12:52 -04:00
parent 242a18e0a8
commit 8ee50178f3
194 changed files with 545 additions and 545 deletions

View File

@ -52,7 +52,7 @@ Here's what you can do to help:
### Additional guidelines and conventions regarding snippets ### Additional guidelines and conventions regarding snippets
- When describing snippets, refer to methods, using their full name. For example, use `Array.reduce()`, instead of `reduce()`. - When describing snippets, refer to methods, using their full name. For example, use `Array.prototype.reduce()`, instead of `reduce()`.
- If your snippet contains argument with default parameters, explain what happens if they are omitted when calling the function and what the default case is. - If your snippet contains argument with default parameters, explain what happens if they are omitted when calling the function and what the default case is.
- If your snippet uses recursion, explain the base cases. - If your snippet uses recursion, explain the base cases.
- Always use `const functionName` for function definitions. - Always use `const functionName` for function definitions.
@ -64,13 +64,13 @@ Here's what you can do to help:
- `num` or `n` for a numeric value (usually as the snippet function's argument). - `num` or `n` for a numeric value (usually as the snippet function's argument).
- `el` for DOM elements (usually as the snippet function's argument). - `el` for DOM elements (usually as the snippet function's argument).
- `val` or `v` for value (usually when iterating a list, mapping, sorting etc.). - `val` or `v` for value (usually when iterating a list, mapping, sorting etc.).
- `acc` for accumulators in `Array.reduce()`. - `acc` for accumulators in `Array.prototype.reduce()`.
- `(a,b)` for the two values compared when using `Array.sort()`. - `(a,b)` for the two values compared when using `Array.prototype.sort()`.
- `i` for indexes. - `i` for indexes.
- `fn` for function arguments. - `fn` for function arguments.
- `nums` for arrays of numbers. - `nums` for arrays of numbers.
- Use `()` if your function takes no arguments. - Use `()` if your function takes no arguments.
- Use `_` if an argument inside some function (e.g. `Array.reduce()`) is not used anywhere in your code. - Use `_` if an argument inside some function (e.g. `Array.prototype.reduce()`) is not used anywhere in your code.
- Specify default parameters for arguments, if necessary. It is preferred to put default parameters last unless you have pretty good reason not to. - Specify default parameters for arguments, if necessary. It is preferred to put default parameters last unless you have pretty good reason not to.
- If your snippet's function takes variadic arguments, use `...args` (although in certain cases, it might be needed to use a different name). - If your snippet's function takes variadic arguments, use `...args` (although in certain cases, it might be needed to use a different name).
- If your snippet function's body is a single statement, omit the `return` keyword and use an expression instead. - If your snippet function's body is a single statement, omit the `return` keyword and use an expression instead.
@ -79,7 +79,7 @@ Here's what you can do to help:
- Always use single quotes for string literals. Use template literals, instead, if necessary. - Always use single quotes for string literals. Use template literals, instead, if necessary.
- If your snippet's code is short enough (around 80 characters), you can make it a single-line function (although not mandatory). Otherwise, use multiple lines. - If your snippet's code is short enough (around 80 characters), you can make it a single-line function (although not mandatory). Otherwise, use multiple lines.
- Prefer using `Array` methods whenever possible. - Prefer using `Array` methods whenever possible.
- Prefer `Array.concat()` instead of `Array.push()` when working with `Array.reduce()`. - Prefer `Array.prototype.concat()` instead of `Array.prototype.push()` when working with `Array.prototype.reduce()`.
- Use strict equality checking (`===` and `!==` instead of `==` and `!=`), unless you specifically have reason not to. - Use strict equality checking (`===` and `!==` instead of `==` and `!=`), unless you specifically have reason not to.
- Prefer using the ternary operator (`condition ? trueResult : falseResult`) instead of `if else` statements whenever possible. - Prefer using the ternary operator (`condition ? trueResult : falseResult`) instead of `if else` statements whenever possible.
- Avoid nesting ternary operators (but you can do it if you feel like you should). - Avoid nesting ternary operators (but you can do it if you feel like you should).

View File

@ -6232,7 +6232,7 @@ console.log(arr); // ['line1', 'line2', 'line3']
Converts a tilde path to an absolute path. Converts a tilde path to an absolute path.
Use `String.replace()` with a regular expression and `OS.homedir()` to replace the `~` in the start of the path with the home directory. Use `String.prototype.replace()` with a regular expression and `OS.homedir()` to replace the `~` in the start of the path with the home directory.
```js ```js
const untildify = str => str.replace(/^~($|\/|\\)/, `${require('os').homedir()}$1`); const untildify = str => str.replace(/^~($|\/|\\)/, `${require('os').homedir()}$1`);
@ -6639,7 +6639,7 @@ functions(new Foo(), true); // ['a', 'b', 'c']
Retrieve a set of properties indicated by the given selectors from an object. Retrieve a set of properties indicated by the given selectors from an object.
Use `Array.map()` for each selector, `String.replace()` to replace square brackets with dots, `String.split('.')` to split each selector, `Array.filter()` to remove empty values and `Array.reduce()` to get the value indicated by it. Use `Array.map()` for each selector, `String.prototype.replace()` to replace square brackets with dots, `String.split('.')` to split each selector, `Array.filter()` to remove empty values and `Array.reduce()` to get the value indicated by it.
```js ```js
const get = (from, ...selectors) => const get = (from, ...selectors) =>
@ -7308,7 +7308,7 @@ capitalize('fooBar', true); // 'Foobar'
Capitalizes the first letter of every word in a string. Capitalizes the first letter of every word in a string.
Use `String.replace()` to match the first character of each word and `String.toUpperCase()` to capitalize it. Use `String.prototype.replace()` to match the first character of each word and `String.toUpperCase()` to capitalize it.
```js ```js
const capitalizeEveryWord = str => str.replace(/\b[a-z]/g, char => char.toUpperCase()); const capitalizeEveryWord = str => str.replace(/\b[a-z]/g, char => char.toUpperCase());
@ -7418,7 +7418,7 @@ decapitalize('FooBar', true); // 'fOOBAR'
Escapes a string for use in HTML. Escapes a string for use in HTML.
Use `String.replace()` with a regexp that matches the characters that need to be escaped, using a callback function to replace each character instance with its associated escaped character using a dictionary (object). Use `String.prototype.replace()` with a regexp that matches the characters that need to be escaped, using a callback function to replace each character instance with its associated escaped character using a dictionary (object).
```js ```js
const escapeHTML = str => const escapeHTML = str =>
@ -7450,7 +7450,7 @@ escapeHTML('<a href="#">Me & you</a>'); // '&lt;a href=&quot;#&quot;&gt;Me &amp;
Escapes a string to use in a regular expression. Escapes a string to use in a regular expression.
Use `String.replace()` to escape special characters. Use `String.prototype.replace()` to escape special characters.
```js ```js
const escapeRegExp = str => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); const escapeRegExp = str => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
@ -7471,7 +7471,7 @@ escapeRegExp('(test)'); // \\(test\\)
Converts a string from camelcase. Converts a string from camelcase.
Use `String.replace()` to remove underscores, hyphens, and spaces and convert words to camelcase. Use `String.prototype.replace()` to remove underscores, hyphens, and spaces and convert words to camelcase.
Omit the second argument to use a default `separator` of `_`. Omit the second argument to use a default `separator` of `_`.
```js ```js
@ -7545,7 +7545,7 @@ isAbsoluteURL('/foo/bar'); // false
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.toLowerCase()`, `String.replace()` with an appropriate regular expression to remove unnecessary characters, `String.split('')`, `Array.sort()` and `Array.join('')` on both strings to normalize them, then check if their normalized forms are equal. Use `String.toLowerCase()`, `String.prototype.replace()` with an appropriate regular expression to remove unnecessary characters, `String.split('')`, `Array.sort()` and `Array.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) => {
@ -7699,7 +7699,7 @@ pad('foobar', 3); // 'foobar'
Returns `true` if the given string is a palindrome, `false` otherwise. Returns `true` if the given string is a palindrome, `false` otherwise.
Convert string `String.toLowerCase()` and use `String.replace()` to remove non-alphanumeric characters from it. Convert string `String.toLowerCase()` and use `String.prototype.replace()` to remove non-alphanumeric characters from it.
Then, use the spread operator (`...`) to split string into individual characters, `Array.reverse()`, `String.join('')` and compare to the original, unreversed string, after converting it `String.tolowerCase()`. Then, use the spread operator (`...`) to split string into individual characters, `Array.reverse()`, `String.join('')` and compare to the original, unreversed string, after converting it `String.tolowerCase()`.
```js ```js
@ -8016,7 +8016,7 @@ truncateString('boomerang', 7); // 'boom...'
Unescapes escaped HTML characters. Unescapes escaped HTML characters.
Use `String.replace()` with a regex that matches the characters that need to be unescaped, using a callback function to replace each escaped character instance with its associated unescaped character using a dictionary (object). Use `String.prototype.replace()` with a regex that matches the characters that need to be unescaped, using a callback function to replace each escaped character instance with its associated unescaped character using a dictionary (object).
```js ```js
const unescapeHTML = str => const unescapeHTML = str =>
@ -8048,7 +8048,7 @@ unescapeHTML('&lt;a href=&quot;#&quot;&gt;Me &amp; you&lt;/a&gt;'); // '<a href=
Joins all given URL segments together, then normalizes the resulting URL. Joins all given URL segments together, then normalizes the resulting URL.
Use `String.join('/')` to combine URL segments, then a series of `String.replace()` calls with various regexps to normalize the resulting URL (remove double slashes, add proper slashes for protocol, remove slashes before parameters, combine parameters with `'&'` and normalize first parameter delimiter). Use `String.join('/')` to combine URL segments, then a series of `String.prototype.replace()` calls with various regexps to normalize the resulting URL (remove double slashes, add proper slashes for protocol, remove slashes before parameters, combine parameters with `'&'` and normalize first parameter delimiter).
```js ```js
const URLJoin = (...args) => const URLJoin = (...args) =>

File diff suppressed because it is too large Load Diff

View File

@ -5,7 +5,7 @@
"type": "snippet", "type": "snippet",
"attributes": { "attributes": {
"fileName": "binarySearch.md", "fileName": "binarySearch.md",
"text": "Use recursion. Similar to `Array.indexOf()` that finds the index of a value within an array.\nThe difference being this operation only works with sorted arrays which offers a major performance boost due to it's logarithmic nature when compared to a linear search or `Array.indexOf()`.\n\nSearch a sorted array by repeatedly dividing the search interval in half.\nBegin with an interval covering the whole array.\nIf the value of the search is less than the item in the middle of the interval, recurse into the lower half. Otherwise recurse into the upper half.\nRepeatedly recurse until the value is found which is the mid or you've recursed to a point that is greater than the length which means the value doesn't exist and return `-1`.", "text": "Use recursion. Similar to `Array.prototype.indexOf()` that finds the index of a value within an array.\nThe difference being this operation only works with sorted arrays which offers a major performance boost due to it's logarithmic nature when compared to a linear search or `Array.prototype.indexOf()`.\n\nSearch a sorted array by repeatedly dividing the search interval in half.\nBegin with an interval covering the whole array.\nIf the value of the search is less than the item in the middle of the interval, recurse into the lower half. Otherwise recurse into the upper half.\nRepeatedly recurse until the value is found which is the mid or you've recursed to a point that is greater than the length which means the value doesn't exist and return `-1`.",
"codeBlocks": [ "codeBlocks": [
"const binarySearch = (arr, val, start = 0, end = arr.length - 1) => {\n if (start > end) return -1;\n const mid = Math.floor((start + end) / 2);\n if (arr[mid] > val) return binarySearch(arr, val, start, mid - 1);\n if (arr[mid] < val) return binarySearch(arr, val, mid + 1, end);\n return mid;\n};", "const binarySearch = (arr, val, start = 0, end = arr.length - 1) => {\n if (start > end) return -1;\n const mid = Math.floor((start + end) / 2);\n if (arr[mid] > val) return binarySearch(arr, val, start, mid - 1);\n if (arr[mid] < val) return binarySearch(arr, val, mid + 1, end);\n return mid;\n};",
"binarySearch([1, 4, 6, 7, 12, 13, 15, 18, 19, 20, 22, 24], 6); // 2\nbinarySearch([1, 4, 6, 7, 12, 13, 15, 18, 19, 20, 22, 24], 21); // -1" "binarySearch([1, 4, 6, 7, 12, 13, 15, 18, 19, 20, 22, 24], 6); // 2\nbinarySearch([1, 4, 6, 7, 12, 13, 15, 18, 19, 20, 22, 24], 21); // -1"
@ -73,7 +73,7 @@
"type": "snippet", "type": "snippet",
"attributes": { "attributes": {
"fileName": "factors.md", "fileName": "factors.md",
"text": "Returns the array of factors of the given `num`. \nIf the second argument is set to `true` returns only the prime factors of `num`.\nIf `num` is `1` or `0` returns an empty array.\nIf `num` is less than `0` returns all the factors of `-int` together with their additive inverses.\n\nUse `Array.from()`, `Array.map()` and `Array.filter()` to find all the factors of `num`.\nIf given `num` is negative, use `Array.reduce()` to add the additive inverses to the array.\nReturn all results if `primes` is `false`, else determine and return only the prime factors using `isPrime` and `Array.filter()`.\nOmit the second argument, `primes`, to return prime and non-prime factors by default.\n\n**Note**:- _Negative numbers are not considered prime._", "text": "Returns the array of factors of the given `num`. \nIf the second argument is set to `true` returns only the prime factors of `num`.\nIf `num` is `1` or `0` returns an empty array.\nIf `num` is less than `0` returns all the factors of `-int` together with their additive inverses.\n\nUse `Array.from()`, `Array.prototype.map()` and `Array.prototype.filter()` to find all the factors of `num`.\nIf given `num` is negative, use `Array.prototype.reduce()` to add the additive inverses to the array.\nReturn all results if `primes` is `false`, else determine and return only the prime factors using `isPrime` and `Array.prototype.filter()`.\nOmit the second argument, `primes`, to return prime and non-prime factors by default.\n\n**Note**:- _Negative numbers are not considered prime._",
"codeBlocks": [ "codeBlocks": [
"const factors = (num, primes = false) => {\n const isPrime = num => {\n const boundary = Math.floor(Math.sqrt(num));\n for (var i = 2; i <= boundary; i++) if (num % i === 0) return false;\n return num >= 2;\n };\n const isNeg = num < 0;\n num = isNeg ? -num : num;\n let array = Array.from({ length: num - 1 })\n .map((val, i) => (num % (i + 2) === 0 ? i + 2 : false))\n .filter(val => val);\n if (isNeg)\n array = array.reduce((acc, val) => {\n acc.push(val);\n acc.push(-val);\n return acc;\n }, []);\n return primes ? array.filter(isPrime) : array;\n};", "const factors = (num, primes = false) => {\n const isPrime = num => {\n const boundary = Math.floor(Math.sqrt(num));\n for (var i = 2; i <= boundary; i++) if (num % i === 0) return false;\n return num >= 2;\n };\n const isNeg = num < 0;\n num = isNeg ? -num : num;\n let array = Array.from({ length: num - 1 })\n .map((val, i) => (num % (i + 2) === 0 ? i + 2 : false))\n .filter(val => val);\n if (isNeg)\n array = array.reduce((acc, val) => {\n acc.push(val);\n acc.push(-val);\n return acc;\n }, []);\n return primes ? array.filter(isPrime) : array;\n};",
"factors(12); // [2,3,4,6,12]\nfactors(12, true); // [2,3]\nfactors(-12); // [2, -2, 3, -3, 4, -4, 6, -6, 12, -12]\nfactors(-12, true); // [2,3]" "factors(12); // [2,3,4,6,12]\nfactors(12, true); // [2,3]\nfactors(-12); // [2, -2, 3, -3, 4, -4, 6, -6, 12, -12]\nfactors(-12, true); // [2,3]"
@ -107,7 +107,7 @@
"type": "snippet", "type": "snippet",
"attributes": { "attributes": {
"fileName": "fibonacciUntilNum.md", "fileName": "fibonacciUntilNum.md",
"text": "Generates an array, containing the Fibonacci sequence, up until the nth term.\n\nCreate an empty array of the specific length, initializing the first two values (`0` and `1`).\nUse `Array.reduce()` to add values into the array, using the sum of the last two values, except for the first two.\nUses a mathematical formula to calculate the length of the array required.", "text": "Generates an array, containing the Fibonacci sequence, up until the nth term.\n\nCreate an empty array of the specific length, initializing the first two values (`0` and `1`).\nUse `Array.prototype.reduce()` to add values into the array, using the sum of the last two values, except for the first two.\nUses a mathematical formula to calculate the length of the array required.",
"codeBlocks": [ "codeBlocks": [
"const fibonacciUntilNum = num => {\n let n = Math.ceil(Math.log(num * Math.sqrt(5) + 1 / 2) / Math.log((Math.sqrt(5) + 1) / 2));\n return Array.from({ length: n }).reduce(\n (acc, val, i) => acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : i),\n []\n );\n};", "const fibonacciUntilNum = num => {\n let n = Math.ceil(Math.log(num * Math.sqrt(5) + 1 / 2) / Math.log((Math.sqrt(5) + 1) / 2));\n return Array.from({ length: n }).reduce(\n (acc, val, i) => acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : i),\n []\n );\n};",
"fibonacciUntilNum(10); // [ 0, 1, 1, 2, 3, 5, 8 ]" "fibonacciUntilNum(10); // [ 0, 1, 1, 2, 3, 5, 8 ]"
@ -260,7 +260,7 @@
"type": "snippet", "type": "snippet",
"attributes": { "attributes": {
"fileName": "quickSort.md", "fileName": "quickSort.md",
"text": "QuickSort an Array (ascending sort by default).\n\nUse recursion. \nUse `Array.filter` and spread operator (`...`) to create an array that all elements with values less than the pivot come before the pivot, and all elements with values greater than the pivot come after it. \nIf the parameter `desc` is truthy, return array sorts in descending order.", "text": "QuickSort an Array (ascending sort by default).\n\nUse recursion. \nUse `Array.prototype.filter` and spread operator (`...`) to create an array that all elements with values less than the pivot come before the pivot, and all elements with values greater than the pivot come after it. \nIf the parameter `desc` is truthy, return array sorts in descending order.",
"codeBlocks": [ "codeBlocks": [
"const quickSort = ([n, ...nums], desc) =>\n isNaN(n)\n ? []\n : [\n ...quickSort(nums.filter(v => (desc ? v > n : v <= n)), desc),\n n,\n ...quickSort(nums.filter(v => (!desc ? v > n : v <= n)), desc)\n ];", "const quickSort = ([n, ...nums], desc) =>\n isNaN(n)\n ? []\n : [\n ...quickSort(nums.filter(v => (desc ? v > n : v <= n)), desc),\n n,\n ...quickSort(nums.filter(v => (!desc ? v > n : v <= n)), desc)\n ];",
"quickSort([4, 1, 3, 2]); // [1,2,3,4]\nquickSort([4, 1, 3, 2], true); // [4,3,2,1]" "quickSort([4, 1, 3, 2]); // [1,2,3,4]\nquickSort([4, 1, 3, 2], true); // [4,3,2,1]"
@ -330,7 +330,7 @@
"type": "snippet", "type": "snippet",
"attributes": { "attributes": {
"fileName": "removeVowels.md", "fileName": "removeVowels.md",
"text": "Returns all the vowels in a `str` replaced by `repl`.\n\nUse `String.replace()` with a regexp to replace all vowels in `str`.\nOmot `repl` to use a default value of `''`.", "text": "Returns all the vowels in a `str` replaced by `repl`.\n\nUse `String.prototype.replace()` with a regexp to replace all vowels in `str`.\nOmot `repl` to use a default value of `''`.",
"codeBlocks": [ "codeBlocks": [
"const removeVowels = (str, repl = '') => str.replace(/[aeiou]/gi, repl);", "const removeVowels = (str, repl = '') => str.replace(/[aeiou]/gi, repl);",
"removeVowels(\"foobAr\"); // \"fbr\"\nremoveVowels(\"foobAr\",\"*\"); // \"f**b*r\"" "removeVowels(\"foobAr\"); // \"fbr\"\nremoveVowels(\"foobAr\",\"*\"); // \"f**b*r\""
@ -347,7 +347,7 @@
"type": "snippet", "type": "snippet",
"attributes": { "attributes": {
"fileName": "solveRPN.md", "fileName": "solveRPN.md",
"text": "Solves the given mathematical expression in [reverse polish notation](https://en.wikipedia.org/wiki/Reverse_Polish_notation).\nThrows appropriate errors if there are unrecognized symbols or the expression is wrong. The valid operators are :- `+`,`-`,`*`,`/`,`^`,`**` (`^`&`**` are the exponential symbols and are same). This snippet does not supports any unary operators.\n\nUse a dictionary, `OPERATORS` to specify each operator's matching mathematical operation.\nUse `String.replace()` with a regular expression to replace `^` with `**`, `String.split()` to tokenize the string and `Array.filter()` to remove empty tokens.\nUse `Array.forEach()` to parse each `symbol`, evaluate it as a numeric value or operator and solve the mathematical expression.\nNumeric values are converted to floating point numbers and pushed to a `stack`, while operators are evaluated using the `OPERATORS` dictionary and pop elements from the `stack` to apply operations.", "text": "Solves the given mathematical expression in [reverse polish notation](https://en.wikipedia.org/wiki/Reverse_Polish_notation).\nThrows appropriate errors if there are unrecognized symbols or the expression is wrong. The valid operators are :- `+`,`-`,`*`,`/`,`^`,`**` (`^`&`**` are the exponential symbols and are same). This snippet does not supports any unary operators.\n\nUse a dictionary, `OPERATORS` to specify each operator's matching mathematical operation.\nUse `String.prototype.replace()` with a regular expression to replace `^` with `**`, `String.prototype.split()` to tokenize the string and `Array.prototype.filter()` to remove empty tokens.\nUse `Array.prototype.forEach()` to parse each `symbol`, evaluate it as a numeric value or operator and solve the mathematical expression.\nNumeric values are converted to floating point numbers and pushed to a `stack`, while operators are evaluated using the `OPERATORS` dictionary and pop elements from the `stack` to apply operations.",
"codeBlocks": [ "codeBlocks": [
"const solveRPN = rpn => {\n const OPERATORS = {\n '*': (a, b) => a * b,\n '+': (a, b) => a + b,\n '-': (a, b) => a - b,\n '/': (a, b) => a / b,\n '**': (a, b) => a ** b\n };\n const [stack, solve] = [\n [],\n rpn\n .replace(/\\^/g, '**')\n .split(/\\s+/g)\n .filter(el => !/\\s+/.test(el) && el !== '')\n ];\n solve.forEach(symbol => {\n if (!isNaN(parseFloat(symbol)) && isFinite(symbol)) {\n stack.push(symbol);\n } else if (Object.keys(OPERATORS).includes(symbol)) {\n const [a, b] = [stack.pop(), stack.pop()];\n stack.push(OPERATORS[symbol](parseFloat(b), parseFloat(a)));\n } else {\n throw `${symbol} is not a recognized symbol`;\n }\n });\n if (stack.length === 1) return stack.pop();\n else throw `${rpn} is not a proper RPN. Please check it and try again`;\n};", "const solveRPN = rpn => {\n const OPERATORS = {\n '*': (a, b) => a * b,\n '+': (a, b) => a + b,\n '-': (a, b) => a - b,\n '/': (a, b) => a / b,\n '**': (a, b) => a ** b\n };\n const [stack, solve] = [\n [],\n rpn\n .replace(/\\^/g, '**')\n .split(/\\s+/g)\n .filter(el => !/\\s+/.test(el) && el !== '')\n ];\n solve.forEach(symbol => {\n if (!isNaN(parseFloat(symbol)) && isFinite(symbol)) {\n stack.push(symbol);\n } else if (Object.keys(OPERATORS).includes(symbol)) {\n const [a, b] = [stack.pop(), stack.pop()];\n stack.push(OPERATORS[symbol](parseFloat(b), parseFloat(a)));\n } else {\n throw `${symbol} is not a recognized symbol`;\n }\n });\n if (stack.length === 1) return stack.pop();\n else throw `${rpn} is not a proper RPN. Please check it and try again`;\n};",
"solveRPN('15 7 1 1 + - / 3 * 2 1 1 + + -'); // 5\nsolveRPN('2 3 ^'); // 8" "solveRPN('15 7 1 1 + - / 3 * 2 1 1 + + -'); // 5\nsolveRPN('2 3 ^'); // 8"

View File

@ -2,8 +2,8 @@
Converts a comma-separated values (CSV) string to a 2D array. Converts a comma-separated values (CSV) string to a 2D array.
Use `Array.slice()` and `Array.indexOf('\n')` to remove the first row (title row) if `omitFirstRow` is `true`. Use `Array.prototype.slice()` and `Array.prototype.indexOf('\n')` to remove the first row (title row) if `omitFirstRow` is `true`.
Use `String.split('\n')` to create a string for each row, then `String.split(delimiter)` to separate the values in each row. Use `String.prototype.split('\n')` to create a string for each row, then `String.prototype.split(delimiter)` to separate the values in each row.
Omit the second argument, `delimiter`, to use a default delimiter of `,`. Omit the second argument, `delimiter`, to use a default delimiter of `,`.
Omit the third argument, `omitFirstRow`, to include the first row (title row) of the CSV string. Omit the third argument, `omitFirstRow`, to include the first row (title row) of the CSV string.

View File

@ -3,9 +3,9 @@
Converts a comma-separated values (CSV) string to a 2D array of objects. Converts a comma-separated values (CSV) string to a 2D array of objects.
The first row of the string is used as the title row. The first row of the string is used as the title row.
Use `Array.slice()` and `Array.indexOf('\n')` and `String.split(delimiter)` to separate the first row (title row) into values. Use `Array.prototype.slice()` and `Array.prototype.indexOf('\n')` and `String.prototype.split(delimiter)` to separate the first row (title row) into values.
Use `String.split('\n')` to create a string for each row, then `Array.map()` and `String.split(delimiter)` to separate the values in each row. Use `String.prototype.split('\n')` to create a string for each row, then `Array.prototype.map()` and `String.prototype.split(delimiter)` to separate the values in each row.
Use `Array.reduce()` to create an object for each row's values, with the keys parsed from the title row. Use `Array.prototype.reduce()` to create an object for each row's values, with the keys parsed from the title row.
Omit the second argument, `delimiter`, to use a default delimiter of `,`. Omit the second argument, `delimiter`, to use a default delimiter of `,`.
```js ```js

View File

@ -2,9 +2,9 @@
Converts an array of objects to a comma-separated values (CSV) string that contains only the `columns` specified. Converts an array of objects to a comma-separated values (CSV) string that contains only the `columns` specified.
Use `Array.join(demiliter)` to combine all the names in `columns` to create the first row. Use `Array.prototype.join(demiliter)` to combine all the names in `columns` to create the first row.
Use `Array.map()` and `Array.reduce()` to create a row for each object, substituting non-existent values with empty strings and only mapping values in `columns`. Use `Array.prototype.map()` and `Array.prototype.reduce()` to create a row for each object, substituting non-existent values with empty strings and only mapping values in `columns`.
Use `Array.join('\n')` to combine all rows into a string. Use `Array.prototype.join('\n')` to combine all rows into a string.
Omit the third argument, `delimiter`, to use a default delimiter of `,`. Omit the third argument, `delimiter`, to use a default delimiter of `,`.
```js ```js

View File

@ -2,7 +2,7 @@
Joins all given URL segments together, then normalizes the resulting URL. Joins all given URL segments together, then normalizes the resulting URL.
Use `String.join('/')` to combine URL segments, then a series of `String.replace()` calls with various regexps to normalize the resulting URL (remove double slashes, add proper slashes for protocol, remove slashes before parameters, combine parameters with `'&'` and normalize first parameter delimiter). Use `String.prototype.join('/')` to combine URL segments, then a series of `String.prototype.replace()` calls with various regexps to normalize the resulting URL (remove double slashes, add proper slashes for protocol, remove slashes before parameters, combine parameters with `'&'` and normalize first parameter delimiter).
```js ```js
const URLJoin = (...args) => const URLJoin = (...args) =>

View File

@ -2,7 +2,7 @@
Returns `true` if the provided predicate function returns `true` for all elements in a collection, `false` otherwise. Returns `true` if the provided predicate function returns `true` for all elements in a collection, `false` otherwise.
Use `Array.every()` to test if all elements in the collection return `true` based on `fn`. Use `Array.prototype.every()` to test if all elements in the collection return `true` based on `fn`.
Omit the second argument, `fn`, to use `Boolean` as a default. Omit the second argument, `fn`, to use `Boolean` as a default.
```js ```js

View File

@ -2,7 +2,7 @@
Check if all elements in an array are equal. Check if all elements in an array are equal.
Use `Array.every()` to check if all the elements of the array are the same as the first one. Use `Array.prototype.every()` to check if all the elements of the array are the same as the first one.
```js ```js
const allEqual = arr => arr.every(val => val === arr[0]); const allEqual = arr => arr.every(val => val === arr[0]);

View File

@ -2,7 +2,7 @@
Returns `true` if the provided predicate function returns `true` for at least one element in a collection, `false` otherwise. Returns `true` if the provided predicate function returns `true` for at least one element in a collection, `false` otherwise.
Use `Array.some()` to test if any elements in the collection return `true` based on `fn`. Use `Array.prototype.some()` to test if any elements in the collection return `true` based on `fn`.
Omit the second argument, `fn`, to use `Boolean` as a default. Omit the second argument, `fn`, to use `Boolean` as a default.
```js ```js

View File

@ -2,8 +2,8 @@
Converts a 2D array to a comma-separated values (CSV) string. Converts a 2D array to a comma-separated values (CSV) string.
Use `Array.map()` and `Array.join(delimiter)` to combine individual 1D arrays (rows) into strings. Use `Array.prototype.map()` and `Array.prototype.join(delimiter)` to combine individual 1D arrays (rows) into strings.
Use `Array.join('\n')` to combine all rows into a CSV string, separating each row with a newline. Use `Array.prototype.join('\n')` to combine all rows into a CSV string, separating each row with a newline.
Omit the second argument, `delimiter`, to use a default delimiter of `,`. Omit the second argument, `delimiter`, to use a default delimiter of `,`.
```js ```js

View File

@ -2,7 +2,7 @@
Converts the given array elements into `<li>` tags and appends them to the list of the given id. Converts the given array elements into `<li>` tags and appends them to the list of the given id.
Use `Array.map()`, `document.querySelector()`, and an anonymous inner closure to create a list of html tags. Use `Array.prototype.map()`, `document.querySelector()`, and an anonymous inner closure to create a list of html tags.
```js ```js
const arrayToHtmlList = (arr, listID) => const arrayToHtmlList = (arr, listID) =>

View File

@ -2,7 +2,7 @@
Creates a function that accepts up to `n` arguments, ignoring any additional arguments. Creates a function that accepts up to `n` arguments, ignoring any additional arguments.
Call the provided function, `fn`, with up to `n` arguments, using `Array.slice(0,n)` and the spread operator (`...`). Call the provided function, `fn`, with up to `n` arguments, using `Array.prototype.slice(0,n)` and the spread operator (`...`).
```js ```js
const ary = (fn, n) => (...args) => fn(...args.slice(0, n)); const ary = (fn, n) => (...args) => fn(...args.slice(0, n));

View File

@ -2,7 +2,7 @@
Returns the average of two or more numbers. Returns the average of two or more numbers.
Use `Array.reduce()` to add each value to an accumulator, initialized with a value of `0`, divide by the `length` of the array. Use `Array.prototype.reduce()` to add each value to an accumulator, initialized with a value of `0`, divide by the `length` of the array.
```js ```js
const average = (...nums) => nums.reduce((acc, val) => acc + val, 0) / nums.length; const average = (...nums) => nums.reduce((acc, val) => acc + val, 0) / nums.length;

View File

@ -2,7 +2,7 @@
Returns the average of an array, after mapping each element to a value using the provided function. Returns the average of an array, after mapping each element to a value using the provided function.
Use `Array.map()` to map each element to the value returned by `fn`, `Array.reduce()` to add each value to an accumulator, initialized with a value of `0`, divide by the `length` of the array. 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`, divide by the `length` of the array.
```js ```js
const averageBy = (arr, fn) => const averageBy = (arr, fn) =>

View File

@ -2,7 +2,7 @@
Splits values into two groups. If an element in `filter` is truthy, the corresponding element in the collection belongs to the first group; otherwise, it belongs to the second group. Splits values into two groups. If an element in `filter` is truthy, the corresponding element in the collection belongs to the first group; otherwise, it belongs to the second group.
Use `Array.reduce()` and `Array.push()` to add elements to groups, based on `filter`. Use `Array.prototype.reduce()` and `Array.prototype.push()` to add elements to groups, based on `filter`.
```js ```js
const bifurcate = (arr, filter) => const bifurcate = (arr, filter) =>

View File

@ -2,7 +2,7 @@
Splits values into two groups according to a predicate function, which specifies which group an element in the input collection belongs to. If the predicate function returns a truthy value, the collection element belongs to the first group; otherwise, it belongs to the second group. Splits values into two groups according to a predicate function, which specifies which group an element in the input collection belongs to. If the predicate function returns a truthy value, the collection element belongs to the first group; otherwise, it belongs to the second group.
Use `Array.reduce()` and `Array.push()` to add elements to groups, based on the value returned by `fn` for each element. Use `Array.prototype.reduce()` and `Array.prototype.push()` to add elements to groups, based on the value returned by `fn` for each element.
```js ```js
const bifurcateBy = (arr, fn) => const bifurcateBy = (arr, fn) =>

View File

@ -2,8 +2,8 @@
Creates a function that invokes `fn` with a given context, optionally adding any additional supplied parameters to the beginning of the arguments. Creates a function that invokes `fn` with a given context, optionally adding any additional supplied parameters to the beginning of the arguments.
Return a `function` that uses `Function.apply()` to apply the given `context` to `fn`. Return a `function` that uses `Function.prototype.apply()` to apply the given `context` to `fn`.
Use `Array.concat()` to prepend any additional supplied parameters to the arguments. Use `Array.prototype.concat()` to prepend any additional supplied parameters to the arguments.
```js ```js
const bind = (fn, context, ...boundArgs) => (...args) => fn.apply(context, [...boundArgs, ...args]); const bind = (fn, context, ...boundArgs) => (...args) => fn.apply(context, [...boundArgs, ...args]);

View File

@ -2,7 +2,7 @@
Binds methods of an object to the object itself, overwriting the existing method. Binds methods of an object to the object itself, overwriting the existing method.
Use `Array.forEach()` to return a `function` that uses `Function.apply()` to apply the given context (`obj`) to `fn` for each function specified. Use `Array.prototype.forEach()` to return a `function` that uses `Function.prototype.apply()` to apply the given context (`obj`) to `fn` for each function specified.
```js ```js
const bindAll = (obj, ...fns) => const bindAll = (obj, ...fns) =>

View File

@ -2,7 +2,7 @@
Creates a function that invokes the method at a given key of an object, optionally adding any additional supplied parameters to the beginning of the arguments. Creates a function that invokes the method at a given key of an object, optionally adding any additional supplied parameters to the beginning of the arguments.
Return a `function` that uses `Function.apply()` to bind `context[fn]` to `context`. Return a `function` that uses `Function.prototype.apply()` to bind `context[fn]` to `context`.
Use the spread operator (`...`) to prepend any additional supplied parameters to the arguments. Use the spread operator (`...`) to prepend any additional supplied parameters to the arguments.
```js ```js

View File

@ -2,7 +2,7 @@
Capitalizes the first letter of a string. Capitalizes the first letter of a string.
Use array destructuring and `String.toUpperCase()` to capitalize first letter, `...rest` to get array of characters after first letter and then `Array.join('')` to make it a string again. Use array destructuring and `String.prototype.toUpperCase()` to capitalize first letter, `...rest` to get array of characters after first letter and then `Array.prototype.join('')` to make it a string again.
Omit the `lowerRest` parameter to keep the rest of the string intact, or set it to `true` to convert to lowercase. Omit the `lowerRest` parameter to keep the rest of the string intact, or set it to `true` to convert to lowercase.
```js ```js

View File

@ -2,7 +2,7 @@
Capitalizes the first letter of every word in a string. Capitalizes the first letter of every word in a string.
Use `String.replace()` to match the first character of each word and `String.toUpperCase()` to capitalize it. Use `String.prototype.replace()` to match the first character of each word and `String.prototype.toUpperCase()` to capitalize it.
```js ```js
const capitalizeEveryWord = str => str.replace(/\b[a-z]/g, char => char.toUpperCase()); const capitalizeEveryWord = str => str.replace(/\b[a-z]/g, char => char.toUpperCase());

View File

@ -2,7 +2,7 @@
Casts the provided value as an array if it's not one. Casts the provided value as an array if it's not one.
Use `Array.isArray()` to determine if `val` is an array and return it as-is or encapsulated in an array accordingly. Use `Array.prototype.isArray()` to determine if `val` is an array and return it as-is or encapsulated in an array accordingly.
```js ```js
const castArray = val => (Array.isArray(val) ? val : [val]); const castArray = val => (Array.isArray(val) ? val : [val]);

View File

@ -3,7 +3,7 @@
Chunks an array into smaller arrays of a specified size. Chunks an array into smaller arrays of a specified size.
Use `Array.from()` to create a new array, that fits the number of chunks that will be produced. Use `Array.from()` to create a new array, that fits the number of chunks that will be produced.
Use `Array.slice()` to map each element of the new array to a chunk the length of `size`. Use `Array.prototype.slice()` to map each element of the new array to a chunk the length of `size`.
If the original array can't be split evenly, the final chunk will contain the remaining elements. If the original array can't be split evenly, the final chunk will contain the remaining elements.
```js ```js

View File

@ -2,7 +2,7 @@
Returns the first non-null/undefined argument. Returns the first non-null/undefined argument.
Use `Array.find()` to return the first non `null`/`undefined` argument. Use `Array.prototype.find()` to return the first non `null`/`undefined` argument.
```js ```js
const coalesce = (...args) => args.find(_ => ![undefined, null].includes(_)); const coalesce = (...args) => args.find(_ => ![undefined, null].includes(_));

View File

@ -2,7 +2,7 @@
Returns a customized coalesce function that returns the first argument that returns `true` from the provided argument validation function. Returns a customized coalesce function that returns the first argument that returns `true` from the provided argument validation function.
Use `Array.find()` to return the first argument that returns `true` from the provided argument validation function. Use `Array.prototype.find()` to return the first argument that returns `true` from the provided argument validation function.
```js ```js
const coalesceFactory = valid => (...args) => args.find(valid); const coalesceFactory = valid => (...args) => args.find(valid);

View File

@ -2,7 +2,7 @@
Removes falsey values from an array. Removes falsey values from an array.
Use `Array.filter()` to filter out falsey values (`false`, `null`, `0`, `""`, `undefined`, and `NaN`). Use `Array.prototype.filter()` to filter out falsey values (`false`, `null`, `0`, `""`, `undefined`, and `NaN`).
```js ```js
const compact = arr => arr.filter(Boolean); const compact = arr => arr.filter(Boolean);

View File

@ -2,7 +2,7 @@
Performs right-to-left function composition. Performs right-to-left function composition.
Use `Array.reduce()` to perform right-to-left function composition. Use `Array.prototype.reduce()` to perform right-to-left function composition.
The last (rightmost) function can accept one or more arguments; the remaining functions must be unary. The last (rightmost) function can accept one or more arguments; the remaining functions must be unary.
```js ```js

View File

@ -2,7 +2,7 @@
Performs left-to-right function composition. Performs left-to-right function composition.
Use `Array.reduce()` to perform left-to-right function composition. Use `Array.prototype.reduce()` to perform left-to-right function composition.
The first (leftmost) function can accept one or more arguments; the remaining functions must be unary. The first (leftmost) function can accept one or more arguments; the remaining functions must be unary.
```js ```js

View File

@ -2,7 +2,7 @@
Accepts a converging function and a list of branching functions and returns a function that applies each branching function to the arguments and the results of the branching functions are passed as arguments to the converging function. Accepts a converging function and a list of branching functions and returns a function that applies each branching function to the arguments and the results of the branching functions are passed as arguments to the converging function.
Use `Array.map()` and `Function.apply()` to apply each function to the given arguments. Use `Array.prototype.map()` and `Function.prototype.apply()` to apply each function to the given arguments.
Use the spread operator (`...`) to call `coverger` with the results of all other functions. Use the spread operator (`...`) to call `coverger` with the results of all other functions.
```js ```js

View File

@ -2,8 +2,8 @@
Groups the elements of an array based on the given function and returns the count of elements in each group. Groups the elements of an array based on the given function and returns the count of elements in each group.
Use `Array.map()` to map the values of an array to a function or property name. Use `Array.prototype.map()` to map the values of an array to a function or property name.
Use `Array.reduce()` to create an object, where the keys are produced from the mapped results. Use `Array.prototype.reduce()` to create an object, where the keys are produced from the mapped results.
```js ```js
const countBy = (arr, fn) => const countBy = (arr, fn) =>

View File

@ -2,7 +2,7 @@
Counts the occurrences of a value in an array. Counts the occurrences of a value in an array.
Use `Array.reduce()` to increment a counter each time you encounter the specific value inside the array. Use `Array.prototype.reduce()` to increment a counter each time you encounter the specific value inside the array.
```js ```js
const countOccurrences = (arr, val) => arr.reduce((a, v) => (v === val ? a + 1 : a), 0); const countOccurrences = (arr, val) => arr.reduce((a, v) => (v === val ? a + 1 : a), 0);

View File

@ -3,10 +3,10 @@
Creates a pub/sub ([publishsubscribe](https://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern)) event hub with `emit`, `on`, and `off` methods. Creates a pub/sub ([publishsubscribe](https://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern)) event hub with `emit`, `on`, and `off` methods.
Use `Object.create(null)` to create an empty `hub` object that does not inherit properties from `Object.prototype`. Use `Object.create(null)` to create an empty `hub` object that does not inherit properties from `Object.prototype`.
For `emit`, resolve the array of handlers based on the `event` argument and then run each one with `Array.forEach()` by passing in the data as an argument. For `emit`, resolve the array of handlers based on the `event` argument and then run each one with `Array.prototype.forEach()` by passing in the data as an argument.
For `on`, create an array for the event if it does not yet exist, then use `Array.push()` to add the handler For `on`, create an array for the event if it does not yet exist, then use `Array.prototype.push()` to add the handler
to the array. to the array.
For `off`, use `Array.findIndex()` to find the index of the handler in the event array and remove it using `Array.splice()`. For `off`, use `Array.prototype.findIndex()` to find the index of the handler in the event array and remove it using `Array.prototype.splice()`.
```js ```js
const createEventHub = () => ({ const createEventHub = () => ({

View File

@ -2,7 +2,7 @@
Creates a debounced function that delays invoking the provided function until at least `ms` milliseconds have elapsed since the last time it was invoked. Creates a debounced function that delays invoking the provided function until at least `ms` milliseconds have elapsed since the last time it was invoked.
Each time the debounced function is invoked, clear the current pending timeout with `clearTimeout()` and use `setTimeout()` to create a new timeout that delays invoking the function until at least `ms` milliseconds has elapsed. Use `Function.apply()` to apply the `this` context to the function and provide the necessary arguments. Each time the debounced function is invoked, clear the current pending timeout with `clearTimeout()` and use `setTimeout()` to create a new timeout that delays invoking the function until at least `ms` milliseconds has elapsed. Use `Function.prototype.apply()` to apply the `this` context to the function and provide the necessary arguments.
Omit the second argument, `ms`, to set the timeout at a default of 0 ms. Omit the second argument, `ms`, to set the timeout at a default of 0 ms.
```js ```js

View File

@ -2,7 +2,7 @@
Decapitalizes the first letter of a string. Decapitalizes the first letter of a string.
Use array destructuring and `String.toLowerCase()` to decapitalize first letter, `...rest` to get array of characters after first letter and then `Array.join('')` to make it a string again. Use array destructuring and `String.toLowerCase()` to decapitalize first letter, `...rest` to get array of characters after first letter and then `Array.prototype.join('')` to make it a string again.
Omit the `upperRest` parameter to keep the rest of the string intact, or set it to `true` to convert to uppercase. Omit the `upperRest` parameter to keep the rest of the string intact, or set it to `true` to convert to uppercase.
```js ```js

View File

@ -4,7 +4,7 @@ Creates a deep clone of an object.
Use recursion. Use recursion.
Use `Object.assign()` and an empty object (`{}`) to create a shallow clone of the original. Use `Object.assign()` and an empty object (`{}`) to create a shallow clone of the original.
Use `Object.keys()` and `Array.forEach()` to determine which key-value pairs need to be deep cloned. Use `Object.keys()` and `Array.prototype.forEach()` to determine which key-value pairs need to be deep cloned.
```js ```js
const deepClone = obj => { const deepClone = obj => {

View File

@ -3,7 +3,7 @@
Deep flattens an array. Deep flattens an array.
Use recursion. Use recursion.
Use `Array.concat()` with an empty array (`[]`) and the spread operator (`...`) to flatten an array. Use `Array.prototype.concat()` with an empty array (`[]`) and the spread operator (`...`) to flatten an array.
Recursively flatten each element that is an array. Recursively flatten each element that is an array.
```js ```js

View File

@ -2,7 +2,7 @@
Assigns default values for all properties in an object that are `undefined`. Assigns default values for all properties in an object that are `undefined`.
Use `Object.assign()` to create a new empty object and copy the original one to maintain key order, use `Array.reverse()` and the spread operator `...` to combine the default values from left to right, finally use `obj` again to overwrite properties that originally had a value. Use `Object.assign()` to create a new empty object and copy the original one to maintain key order, use `Array.prototype.reverse()` and the spread operator `...` to combine the default values from left to right, finally use `obj` again to overwrite properties that originally had a value.
```js ```js
const defaults = (obj, ...defs) => Object.assign({}, obj, ...defs.reverse(), obj); const defaults = (obj, ...defs) => Object.assign({}, obj, ...defs.reverse(), obj);

View File

@ -2,7 +2,7 @@
Returns the difference between two arrays. Returns the difference between two arrays.
Create a `Set` from `b`, then use `Array.filter()` on `a` to only keep values not contained in `b`. Create a `Set` from `b`, then use `Array.prototype.filter()` on `a` to only keep values not contained in `b`.
```js ```js
const difference = (a, b) => { const difference = (a, b) => {

View File

@ -2,7 +2,7 @@
Returns the difference between two arrays, after applying the provided function to each array element of both. Returns the difference between two arrays, after applying the provided function to each array element of both.
Create a `Set` by applying `fn` to each element in `b`, then use `Array.filter()` in combination with `fn` on `a` to only keep values not contained in the previously created set. Create a `Set` by applying `fn` to each element in `b`, then use `Array.prototype.filter()` in combination with `fn` on `a` to only keep values not contained in the previously created set.
```js ```js
const differenceBy = (a, b, fn) => { const differenceBy = (a, b, fn) => {

View File

@ -2,7 +2,7 @@
Filters out all values from an array for which the comparator function does not return `true`. Filters out all values from an array for which the comparator function does not return `true`.
Use `Array.filter()` and `Array.findIndex()` to find the appropriate values. Use `Array.prototype.filter()` and `Array.prototype.findIndex()` to find the appropriate values.
```js ```js
const differenceWith = (arr, val, comp) => arr.filter(a => val.findIndex(b => comp(a, b)) === -1); const differenceWith = (arr, val, comp) => arr.filter(a => val.findIndex(b => comp(a, b)) === -1);

View File

@ -3,7 +3,7 @@
Returns the target value in a nested JSON object, based on the given key. Returns the target value in a nested JSON object, based on the given key.
Use the `in` operator to check if `target` exists in `obj`. Use the `in` operator to check if `target` exists in `obj`.
If found, return the value of `obj[target]`, otherwise use `Object.values(obj)` and `Array.reduce()` to recursively call `dig` on each nested object until the first matching key/value pair is found. If found, return the value of `obj[target]`, otherwise use `Object.values(obj)` and `Array.prototype.reduce()` to recursively call `dig` on each nested object until the first matching key/value pair is found.
```js ```js
const dig = (obj, target) => const dig = (obj, target) =>

View File

@ -3,7 +3,7 @@
Converts a number to an array of digits. Converts a number to an array of digits.
Convert the number to a string, using the spread operator (`...`) to build an array. Convert the number to a string, using the spread operator (`...`) to build an array.
Use `Array.map()` and `parseInt()` to transform each value to an integer. Use `Array.prototype.map()` and `parseInt()` to transform each value to an integer.
```js ```js
const digitize = n => [...`${n}`].map(i => parseInt(i)); const digitize = n => [...`${n}`].map(i => parseInt(i));

View File

@ -2,7 +2,7 @@
Returns a new array with `n` elements removed from the left. Returns a new array with `n` elements removed from the left.
Use `Array.slice()` to slice the remove the specified number of elements from the left. Use `Array.prototype.slice()` to slice the remove the specified number of elements from the left.
```js ```js
const drop = (arr, n = 1) => arr.slice(n); const drop = (arr, n = 1) => arr.slice(n);

View File

@ -2,7 +2,7 @@
Returns a new array with `n` elements removed from the right. Returns a new array with `n` elements removed from the right.
Use `Array.slice()` to slice the remove the specified number of elements from the right. Use `Array.prototype.slice()` to slice the remove the specified number of elements from the right.
```js ```js
const dropRight = (arr, n = 1) => arr.slice(0, -n); const dropRight = (arr, n = 1) => arr.slice(0, -n);

View File

@ -2,7 +2,7 @@
Removes elements from the end of an array until the passed function returns `true`. Returns the remaining elements in the array. Removes elements from the end of an array until the passed function returns `true`. Returns the remaining elements in the array.
Loop through the array, using `Array.slice()` to drop the last element of the array until the returned value from the function is `true`. Loop through the array, using `Array.prototype.slice()` to drop the last element of the array until the returned value from the function is `true`.
Returns the remaining elements. Returns the remaining elements.
```js ```js

View File

@ -2,7 +2,7 @@
Removes elements in an array until the passed function returns `true`. Returns the remaining elements in the array. Removes elements in an array until the passed function returns `true`. Returns the remaining elements in the array.
Loop through the array, using `Array.slice()` to drop the first element of the array until the returned value from the function is `true`. Loop through the array, using `Array.prototype.slice()` to drop the first element of the array until the returned value from the function is `true`.
Returns the remaining elements. Returns the remaining elements.
```js ```js

View File

@ -4,7 +4,7 @@ Performs a deep comparison between two values to determine if they are equivalen
Check if the two values are identical, if they are both `Date` objects with the same time, using `Date.getTime()` or if they are both non-object values with an equivalent value (strict comparison). Check if the two values are identical, if they are both `Date` objects with the same time, using `Date.getTime()` or if they are both non-object values with an equivalent value (strict comparison).
Check if only one value is `null` or `undefined` or if their prototypes differ. Check if only one value is `null` or `undefined` or if their prototypes differ.
If none of the above conditions are met, use `Object.keys()` to check if both values have the same number of keys, then use `Array.every()` to check if every key in the first value exists in the second one and if they are equivalent by calling this method recursively. If none of the above conditions are met, use `Object.keys()` to check if both values have the same number of keys, then use `Array.prototype.every()` to check if every key in the first value exists in the second one and if they are equivalent by calling this method recursively.
```js ```js
const equals = (a, b) => { const equals = (a, b) => {

View File

@ -2,7 +2,7 @@
Escapes a string for use in HTML. Escapes a string for use in HTML.
Use `String.replace()` with a regexp that matches the characters that need to be escaped, using a callback function to replace each character instance with its associated escaped character using a dictionary (object). Use `String.prototype.replace()` with a regexp that matches the characters that need to be escaped, using a callback function to replace each character instance with its associated escaped character using a dictionary (object).
```js ```js
const escapeHTML = str => const escapeHTML = str =>

View File

@ -2,7 +2,7 @@
Escapes a string to use in a regular expression. Escapes a string to use in a regular expression.
Use `String.replace()` to escape special characters. Use `String.prototype.replace()` to escape special characters.
```js ```js
const escapeRegExp = str => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); const escapeRegExp = str => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');

View File

@ -2,7 +2,7 @@
Returns every nth element in an array. Returns every nth element in an array.
Use `Array.filter()` to create a new array that contains every nth element of a given array. Use `Array.prototype.filter()` to create a new array that contains every nth element of a given array.
```js ```js
const everyNth = (arr, nth) => arr.filter((e, i) => i % nth === nth - 1); const everyNth = (arr, nth) => arr.filter((e, i) => i % nth === nth - 1);

View File

@ -2,8 +2,8 @@
Extends a 3-digit color code to a 6-digit color code. Extends a 3-digit color code to a 6-digit color code.
Use `Array.map()`, `String.split()` and `Array.join()` to join the mapped array for converting a 3-digit RGB notated hexadecimal color-code to the 6-digit form. Use `Array.prototype.map()`, `String.prototype.split()` and `Array.prototype.join()` to join the mapped array for converting a 3-digit RGB notated hexadecimal color-code to the 6-digit form.
`Array.slice()` is used to remove `#` from string start since it's added once. `Array.prototype.slice()` is used to remove `#` from string start since it's added once.
```js ```js
const extendHex = shortHex => const extendHex = shortHex =>

View File

@ -3,7 +3,7 @@
Generates an array, containing the Fibonacci sequence, up until the nth term. Generates an array, containing the Fibonacci sequence, up until the nth term.
Create an empty array of the specific length, initializing the first two values (`0` and `1`). Create an empty array of the specific length, initializing the first two values (`0` and `1`).
Use `Array.reduce()` to add values into the array, using the sum of the last two values, except for the first two. Use `Array.prototype.reduce()` to add values into the array, using the sum of the last two values, except for the first two.
```js ```js
const fibonacci = n => const fibonacci = n =>

View File

@ -2,7 +2,7 @@
Filters out the non-unique values in an array. Filters out the non-unique values in an array.
Use `Array.filter()` for an array containing only the unique values. Use `Array.prototype.filter()` for an array containing only the unique values.
```js ```js
const filterNonUnique = arr => arr.filter(i => arr.indexOf(i) === arr.lastIndexOf(i)); const filterNonUnique = arr => arr.filter(i => arr.indexOf(i) === arr.lastIndexOf(i));

View File

@ -2,7 +2,7 @@
Filters out the non-unique values in an array, based on a provided comparator function. Filters out the non-unique values in an array, based on a provided comparator function.
Use `Array.filter()` and `Array.every()` for an array containing only the unique values, based on the comparator function, `fn`. Use `Array.prototype.filter()` and `Array.prototype.every()` for an array containing only the unique values, based on the comparator function, `fn`.
The comparator function takes four arguments: the values of the two elements being compared and their indexes. The comparator function takes four arguments: the values of the two elements being compared and their indexes.
```js ```js

View File

@ -2,7 +2,7 @@
Returns the first key that satisfies the provided testing function. Otherwise `undefined` is returned. Returns the first key that satisfies the provided testing function. Otherwise `undefined` is returned.
Use `Object.keys(obj)` to get all the properties of the object, `Array.find()` to test the provided function for each key-value pair. The callback receives three arguments - the value, the key and the object. Use `Object.keys(obj)` to get all the properties of the object, `Array.prototype.find()` to test the provided function for each key-value pair. The callback receives three arguments - the value, the key and the object.
```js ```js
const findKey = (obj, fn) => Object.keys(obj).find(key => fn(obj[key], key, obj)); const findKey = (obj, fn) => Object.keys(obj).find(key => fn(obj[key], key, obj));

View File

@ -2,7 +2,7 @@
Returns the last element for which the provided function returns a truthy value. Returns the last element for which the provided function returns a truthy value.
Use `Array.filter()` to remove elements for which `fn` returns falsey values, `Array.pop()` to get the last one. Use `Array.prototype.filter()` to remove elements for which `fn` returns falsey values, `Array.prototype.pop()` to get the last one.
```js ```js
const findLast = (arr, fn) => arr.filter(fn).pop(); const findLast = (arr, fn) => arr.filter(fn).pop();

View File

@ -2,8 +2,8 @@
Returns the index of the last element for which the provided function returns a truthy value. Returns the index of the last element for which the provided function returns a truthy value.
Use `Array.map()` to map each element to an array with its index and value. Use `Array.prototype.map()` to map each element to an array with its index and value.
Use `Array.filter()` to remove elements for which `fn` returns falsey values, `Array.pop()` to get the last one. Use `Array.prototype.filter()` to remove elements for which `fn` returns falsey values, `Array.prototype.pop()` to get the last one.
```js ```js
const findLastIndex = (arr, fn) => const findLastIndex = (arr, fn) =>

View File

@ -3,7 +3,7 @@
Returns the last key that satisfies the provided testing function. Returns the last key that satisfies the provided testing function.
Otherwise `undefined` is returned. Otherwise `undefined` is returned.
Use `Object.keys(obj)` to get all the properties of the object, `Array.reverse()` to reverse their order and `Array.find()` to test the provided function for each key-value pair. Use `Object.keys(obj)` to get all the properties of the object, `Array.prototype.reverse()` to reverse their order and `Array.prototype.find()` to test the provided function for each key-value pair.
The callback receives three arguments - the value, the key and the object. The callback receives three arguments - the value, the key and the object.
```js ```js

View File

@ -3,7 +3,7 @@
Flattens an array up to the specified depth. Flattens an array up to the specified depth.
Use recursion, decrementing `depth` by 1 for each level of depth. Use recursion, decrementing `depth` by 1 for each level of depth.
Use `Array.reduce()` and `Array.concat()` to merge elements or arrays. Use `Array.prototype.reduce()` and `Array.prototype.concat()` to merge elements or arrays.
Base case, for `depth` equal to `1` stops recursion. Base case, for `depth` equal to `1` stops recursion.
Omit the second argument, `depth` to flatten only to a depth of `1` (single flatten). Omit the second argument, `depth` to flatten only to a depth of `1` (single flatten).

View File

@ -3,7 +3,7 @@
Flatten an object with the paths for keys. Flatten an object with the paths for keys.
Use recursion. Use recursion.
Use `Object.keys(obj)` combined with `Array.reduce()` to convert every leaf node to a flattened path node. Use `Object.keys(obj)` combined with `Array.prototype.reduce()` to convert every leaf node to a flattened path node.
If the value of a key is an object, the function calls itself with the appropriate `prefix` to create the path using `Object.assign()`. If the value of a key is an object, the function calls itself with the appropriate `prefix` to create the path using `Object.assign()`.
Otherwise, it adds the appropriate prefixed key-value pair to the accumulator object. Otherwise, it adds the appropriate prefixed key-value pair to the accumulator object.
You should always omit the second argument, `prefix`, unless you want every key to have a prefix. You should always omit the second argument, `prefix`, unless you want every key to have a prefix.

View File

@ -2,7 +2,7 @@
Executes a provided function once for each array element, starting from the array's last element. Executes a provided function once for each array element, starting from the array's last element.
Use `Array.slice(0)` to clone the given array, `Array.reverse()` to reverse it and `Array.forEach()` to iterate over the reversed array. Use `Array.prototype.slice(0)` to clone the given array, `Array.prototype.reverse()` to reverse it and `Array.prototype.forEach()` to iterate over the reversed array.
```js ```js
const forEachRight = (arr, callback) => const forEachRight = (arr, callback) =>

View File

@ -2,7 +2,7 @@
Iterates over all own properties of an object, running a callback for each one. Iterates over all own properties of an object, running a callback for each one.
Use `Object.keys(obj)` to get all the properties of the object, `Array.forEach()` to run the provided function for each key-value pair. The callback receives three arguments - the value, the key and the object. Use `Object.keys(obj)` to get all the properties of the object, `Array.prototype.forEach()` to run the provided function for each key-value pair. The callback receives three arguments - the value, the key and the object.
```js ```js
const forOwn = (obj, fn) => Object.keys(obj).forEach(key => fn(obj[key], key, obj)); const forOwn = (obj, fn) => Object.keys(obj).forEach(key => fn(obj[key], key, obj));

View File

@ -2,7 +2,7 @@
Iterates over all own properties of an object in reverse, running a callback for each one. Iterates over all own properties of an object in reverse, running a callback for each one.
Use `Object.keys(obj)` to get all the properties of the object, `Array.reverse()` to reverse their order and `Array.forEach()` to run the provided function for each key-value pair. The callback receives three arguments - the value, the key and the object. Use `Object.keys(obj)` to get all the properties of the object, `Array.prototype.reverse()` to reverse their order and `Array.prototype.forEach()` to run the provided function for each key-value pair. The callback receives three arguments - the value, the key and the object.
```js ```js
const forOwnRight = (obj, fn) => const forOwnRight = (obj, fn) =>

View File

@ -3,9 +3,9 @@
Returns the human readable format of the given number of milliseconds. Returns the human readable format of the given number of milliseconds.
Divide `ms` with the appropriate values to obtain the appropriate values for `day`, `hour`, `minute`, `second` and `millisecond`. Divide `ms` with the appropriate values to obtain the appropriate values for `day`, `hour`, `minute`, `second` and `millisecond`.
Use `Object.entries()` with `Array.filter()` to keep only non-zero values. Use `Object.entries()` with `Array.prototype.filter()` to keep only non-zero values.
Use `Array.map()` to create the string for each value, pluralizing appropriately. Use `Array.prototype.map()` to create the string for each value, pluralizing appropriately.
Use `String.join(', ')` to combine the values into a string. Use `String.prototype.join(', ')` to combine the values into a string.
```js ```js
const formatDuration = ms => { const formatDuration = ms => {

View File

@ -2,7 +2,7 @@
Converts a string from camelcase. Converts a string from camelcase.
Use `String.replace()` to remove underscores, hyphens, and spaces and convert words to camelcase. Use `String.prototype.replace()` to remove underscores, hyphens, and spaces and convert words to camelcase.
Omit the second argument to use a default `separator` of `_`. Omit the second argument to use a default `separator` of `_`.
```js ```js

View File

@ -4,7 +4,7 @@ Returns an array of function property names from own (and optionally inherited)
Use `Object.keys(obj)` to iterate over the object's own properties. Use `Object.keys(obj)` to iterate over the object's own properties.
If `inherited` is `true`, use `Object.get.PrototypeOf(obj)` to also get the object's inherited properties. If `inherited` is `true`, use `Object.get.PrototypeOf(obj)` to also get the object's inherited properties.
Use `Array.filter()` to keep only those properties that are functions. Use `Array.prototype.filter()` to keep only those properties that are functions.
Omit the second argument, `inherited`, to not include inherited properties by default. Omit the second argument, `inherited`, to not include inherited properties by default.
```js ```js

View File

@ -3,7 +3,7 @@
Initializes an array containing the numbers in the specified range where `start` and `end` are inclusive and the ratio between two terms is `step`. Initializes an array containing the numbers in the specified range where `start` and `end` are inclusive and the ratio between two terms is `step`.
Returns an error if `step` equals `1`. Returns an error if `step` equals `1`.
Use `Array.from()`, `Math.log()` and `Math.floor()` to create an array of the desired length, `Array.map()` to fill with the desired values in a range. Use `Array.from()`, `Math.log()` and `Math.floor()` to create an array of the desired length, `Array.prototype.map()` to fill with the desired values in a range.
Omit the second argument, `start`, to use a default value of `1`. Omit the second argument, `start`, to use a default value of `1`.
Omit the third argument, `step`, to use a default value of `2`. Omit the third argument, `step`, to use a default value of `2`.

View File

@ -2,7 +2,7 @@
Retrieve a set of properties indicated by the given selectors from an object. Retrieve a set of properties indicated by the given selectors from an object.
Use `Array.map()` for each selector, `String.replace()` to replace square brackets with dots, `String.split('.')` to split each selector, `Array.filter()` to remove empty values and `Array.reduce()` to get the value indicated by it. Use `Array.prototype.map()` for each selector, `String.prototype.replace()` to replace square brackets with dots, `String.prototype.split('.')` to split each selector, `Array.prototype.filter()` to remove empty values and `Array.prototype.reduce()` to get the value indicated by it.
```js ```js
const get = (from, ...selectors) => const get = (from, ...selectors) =>

View File

@ -2,7 +2,7 @@
Returns a string of the form `HH:MM:SS` from a `Date` object. Returns a string of the form `HH:MM:SS` from a `Date` object.
Use `Date.toString()` and `String.slice()` to get the `HH:MM:SS` part of a given `Date` object. Use `Date.prototype.toString()` and `String.prototype.slice()` to get the `HH:MM:SS` part of a given `Date` object.
```js ```js
const getColonTimeFromDate = date => date.toTimeString().slice(0, 8); const getColonTimeFromDate = date => date.toTimeString().slice(0, 8);

View File

@ -2,7 +2,7 @@
Returns an object containing the parameters of the current URL. Returns an object containing the parameters of the current URL.
Use `String.match()` with an appropriate regular expression to get all key-value pairs, `Array.reduce()` to map and combine them into a single object. Use `String.match()` with an appropriate regular expression to get all key-value pairs, `Array.prototype.reduce()` to map and combine them into a single object.
Pass `location.search` as the argument to apply to the current `url`. Pass `location.search` as the argument to apply to the current `url`.
```js ```js

View File

@ -2,8 +2,8 @@
Groups the elements of an array based on the given function. Groups the elements of an array based on the given function.
Use `Array.map()` to map the values of an array to a function or property name. Use `Array.prototype.map()` to map the values of an array to a function or property name.
Use `Array.reduce()` to create an object, where the keys are produced from the mapped results. Use `Array.prototype.reduce()` to create an object, where the keys are produced from the mapped results.
```js ```js
const groupBy = (arr, fn) => const groupBy = (arr, fn) =>

View File

@ -2,7 +2,7 @@
Check if the current process's arguments contain the specified flags. Check if the current process's arguments contain the specified flags.
Use `Array.every()` and `Array.includes()` to check if `process.argv` contains all the specified flags. Use `Array.prototype.every()` and `Array.prototype.includes()` to check if `process.argv` contains all the specified flags.
Use a regular expression to test if the specified flags are prefixed with `-` or `--` and prefix them accordingly. Use a regular expression to test if the specified flags are prefixed with `-` or `--` and prefix them accordingly.
```js ```js

View File

@ -2,7 +2,7 @@
Redirects the page to HTTPS if its currently in HTTP. Also, pressing the back button doesn't take it back to the HTTP page as its replaced in the history. Redirects the page to HTTPS if its currently in HTTP. Also, pressing the back button doesn't take it back to the HTTP page as its replaced in the history.
Use `location.protocol` to get the protocol currently being used. If it's not HTTPS, use `location.replace()` to replace the existing page with the HTTPS version of the page. Use `location.href` to get the full address, split it with `String.split()` and remove the protocol part of the URL. Use `location.protocol` to get the protocol currently being used. If it's not HTTPS, use `location.replace()` to replace the existing page with the HTTPS version of the page. Use `location.href` to get the full address, split it with `String.prototype.split()` and remove the protocol part of the URL.
```js ```js
const httpsRedirect = () => { const httpsRedirect = () => {

View File

@ -3,7 +3,7 @@
Returns all indices of `val` in an array. Returns all indices of `val` in an array.
If `val` never occurs, returns `[]`. If `val` never occurs, returns `[]`.
Use `Array.reduce()` to loop over elements and store indices for matching elements. Use `Array.prototype.reduce()` to loop over elements and store indices for matching elements.
Return the array of indices. Return the array of indices.
```js ```js

View File

@ -2,7 +2,7 @@
Initializes a 2D array of given width and height and value. Initializes a 2D array of given width and height and value.
Use `Array.map()` to generate h rows where each is a new array of size w initialize with value. If the value is not provided, default to `null`. Use `Array.prototype.map()` to generate h rows where each is a new array of size w initialize with value. If the value is not provided, default to `null`.
```js ```js
const initialize2DArray = (w, h, val = null) => const initialize2DArray = (w, h, val = null) =>

View File

@ -2,7 +2,7 @@
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.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`. You can omit `start` to use a default value of `0`.
You can omit `step` to use a default value of `1`. You can omit `step` to use a default value of `1`.

View File

@ -3,7 +3,7 @@
Create a n-dimensional array with given value. Create a n-dimensional array with given value.
Use recursion. Use recursion.
Use `Array.map()` to generate rows where each is a new array initialized using `initializeNDArray`. Use `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) =>

View File

@ -2,7 +2,7 @@
Returns a list of elements that exist in both arrays. Returns a list of elements that exist in both arrays.
Create a `Set` from `b`, then use `Array.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`.
```js ```js
const intersection = (a, b) => { const intersection = (a, b) => {

View File

@ -2,7 +2,7 @@
Returns a list of elements that exist in both arrays, after applying the provided function to each array element of both. Returns a list of 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.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`, then 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) => {

View File

@ -2,7 +2,7 @@
Returns a list of elements that exist in both arrays, using a provided comparator function. Returns a list of elements that exist in both arrays, using a provided comparator function.
Use `Array.filter()` and `Array.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);

View File

@ -2,7 +2,7 @@
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. 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.
Use `Object.keys()` and `Array.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.
```js ```js

View File

@ -2,7 +2,7 @@
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.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()`, and 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

@ -2,7 +2,7 @@
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.toLowerCase()`, `String.replace()` with an appropriate regular expression to remove unnecessary characters, `String.split('')`, `Array.sort()` and `Array.join('')` on both strings to normalize them, then check if their normalized forms are equal. Use `String.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.
```js ```js
const isAnagram = (str1, str2) => { const isAnagram = (str1, str2) => {

View File

@ -2,7 +2,7 @@
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.
Use `Array.includes()` on the `typeof` values of both `window` and `document` (globals usually only available in a browser environment unless they were explicitly defined), which will return `true` if one of them is `undefined`. Use `Array.prototype.includes()` on the `typeof` values of both `window` and `document` (globals usually only available in a browser environment unless they were explicitly defined), which will return `true` if one of them is `undefined`.
`typeof` allows globals to be checked for existence without throwing a `ReferenceError`. `typeof` allows globals to be checked for existence without throwing a `ReferenceError`.
If both of them are not `undefined`, then the current environment is assumed to be a browser. If both of them are not `undefined`, then the current environment is assumed to be a browser.

View File

@ -2,7 +2,7 @@
Returns a boolean determining if the passed value is primitive or not. Returns a boolean determining if the passed value is primitive or not.
Use `Array.includes()` on an array of type strings which are not primitive, Use `Array.prototype.includes()` on an array of type strings which are not primitive,
supplying the type using `typeof`. supplying the type using `typeof`.
Since `typeof null` evaluates to `'object'`, it needs to be directly compared. Since `typeof null` evaluates to `'object'`, it needs to be directly compared.

View File

@ -2,7 +2,7 @@
Checks if a string is upper case. Checks if a string is upper case.
Convert the given string to upper case, using `String.toUpperCase()` and compare it to the original. Convert the given string to upper case, using `String.prototype.toUpperCase()` and compare it to the original.
```js ```js

View File

@ -3,7 +3,7 @@
Joins all elements of an array into a string and returns this string. Joins all elements of an array into a string and returns this string.
Uses a separator and an end separator. Uses a separator and an end separator.
Use `Array.reduce()` to combine elements into a string. Use `Array.prototype.reduce()` to combine elements into a string.
Omit the second argument, `separator`, to use a default separator of `','`. Omit the second argument, `separator`, to use a default separator of `','`.
Omit the third argument, `end`, to use the same value as `separator` by default. Omit the third argument, `end`, to use the same value as `separator` by default.

View File

@ -4,7 +4,7 @@ Takes any number of iterable objects or objects with a `length` property and ret
If multiple objects have the same length, the first one will be returned. If multiple objects have the same length, the first one will be returned.
Returns `undefined` if no arguments are provided. Returns `undefined` if no arguments are provided.
Use `Array.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.
```js ```js
const longestItem = (val, ...vals) => const longestItem = (val, ...vals) =>

View File

@ -2,7 +2,7 @@
Creates a new object from the specified object, where all the keys are in lowercase. Creates a new object from the specified object, where all the keys are in lowercase.
Use `Object.keys()` and `Array.reduce()` to create a new object from the specified object. Use `Object.keys()` and `Array.prototype.reduce()` to create a new object from the specified object.
Convert each key in the original object to lowercase, using `String.toLowerCase()`. Convert each key in the original object to lowercase, using `String.toLowerCase()`.
```js ```js

View File

@ -2,9 +2,9 @@
Implementation of the [Luhn Algorithm](https://en.wikipedia.org/wiki/Luhn_algorithm) used to validate a variety of identification numbers, such as credit card numbers, IMEI numbers, National Provider Identifier numbers etc. Implementation of the [Luhn Algorithm](https://en.wikipedia.org/wiki/Luhn_algorithm) used to validate a variety of identification numbers, such as credit card numbers, IMEI numbers, National Provider Identifier numbers etc.
Use `String.split('')`, `Array.reverse()` and `Array.map()` in combination with `parseInt()` to obtain an array of digits. Use `String.prototype.split('')`, `Array.prototype.reverse()` and `Array.prototype.map()` in combination with `parseInt()` to obtain an array of digits.
Use `Array.splice(0,1)` to obtain the last digit. Use `Array.prototype.splice(0,1)` to obtain the last digit.
Use `Array.reduce()` to implement the Luhn Algorithm. Use `Array.prototype.reduce()` to implement the Luhn Algorithm.
Return `true` if `sum` is divisible by `10`, `false` otherwise. Return `true` if `sum` is divisible by `10`, `false` otherwise.

View File

@ -3,7 +3,7 @@
Creates an object with keys generated by running the provided function for each key and the same values as the provided object. Creates an object with keys generated by running the provided function for each key and the same values as the provided object.
Use `Object.keys(obj)` to iterate over the object's keys. Use `Object.keys(obj)` to iterate over the object's keys.
Use `Array.reduce()` to create a new object with the same values and mapped keys using `fn`. Use `Array.prototype.reduce()` to create a new object with the same values and mapped keys using `fn`.
```js ```js
const mapKeys = (obj, fn) => const mapKeys = (obj, fn) =>

View File

@ -2,8 +2,8 @@
Creates a new string with the results of calling a provided function on every character in the calling string. Creates a new string with the results of calling a provided function on every character in the calling string.
Use `String.split('')` and `Array.map()` to call the provided function, `fn`, for each character in `str`. Use `String.prototype.split('')` and `Array.prototype.map()` to call the provided function, `fn`, for each character in `str`.
Use `Array.join('')` to recombine the array of characters into a string. Use `Array.prototype.join('')` to recombine the array of characters into a string.
The callback function, `fn`, takes three arguments (the current character, the index of the current character and the string `mapString` was called upon). The callback function, `fn`, takes three arguments (the current character, the index of the current character and the string `mapString` was called upon).
```js ```js

View File

@ -3,7 +3,7 @@
Creates an object with the same keys as the provided object and values generated by running the provided function for each value. Creates an object with the same keys as the provided object and values generated by running the provided function for each value.
Use `Object.keys(obj)` to iterate over the object's keys. Use `Object.keys(obj)` to iterate over the object's keys.
Use `Array.reduce()` to create a new object with the same keys and mapped values using `fn`. Use `Array.prototype.reduce()` to create a new object with the same keys and mapped values using `fn`.
```js ```js
const mapValues = (obj, fn) => const mapValues = (obj, fn) =>

View File

@ -2,7 +2,7 @@
Replaces all but the last `num` of characters with the specified mask character. Replaces all but the last `num` of characters with the specified mask character.
Use `String.slice()` to grab the portion of the characters that will remain unmasked and use `String.padStart()` to fill the beginning of the string with the mask character up to the original length. Use `String.prototype.slice()` to grab the portion of the characters that will remain unmasked and use `String.padStart()` to fill the beginning of the string with the mask character up to the original length.
Omit the second argument, `num`, to keep a default of `4` characters unmasked. If `num` is negative, the unmasked characters will be at the start of the string. Omit the second argument, `num`, to keep a default of `4` characters unmasked. If `num` is negative, the unmasked characters will be at the start of the string.
Omit the third argument, `mask`, to use a default character of `'*'` for the mask. Omit the third argument, `mask`, to use a default character of `'*'` for the mask.

View File

@ -2,7 +2,7 @@
Compares two objects to determine if the first one contains equivalent property values to the second one. Compares two objects to determine if the first one contains equivalent property values to the second one.
Use `Object.keys(source)` to get all the keys of the second object, then `Array.every()`, `Object.hasOwnProperty()` and strict comparison to determine if all keys exist in the first object and have the same values. Use `Object.keys(source)` to get all the keys of the second object, then `Array.prototype.every()`, `Object.hasOwnProperty()` and strict comparison to determine if all keys exist in the first object and have the same values.
```js ```js
const matches = (obj, source) => const matches = (obj, source) =>

View File

@ -2,7 +2,7 @@
Compares two objects to determine if the first one contains equivalent property values to the second one, based on a provided function. Compares two objects to determine if the first one contains equivalent property values to the second one, based on a provided function.
Use `Object.keys(source)` to get all the keys of the second object, then `Array.every()`, `Object.hasOwnProperty()` and the provided function to determine if all keys exist in the first object and have equivalent values. Use `Object.keys(source)` to get all the keys of the second object, then `Array.prototype.every()`, `Object.hasOwnProperty()` and the provided function to determine if all keys exist in the first object and have equivalent values.
If no function is provided, the values will be compared using the equality operator. If no function is provided, the values will be compared using the equality operator.
```js ```js

View File

@ -2,7 +2,7 @@
Returns the maximum value of an array, after mapping each element to a value using the provided function. Returns the maximum value of an array, after mapping each element to a value using the provided function.
Use `Array.map()` to map each element to the value returned by `fn`, `Math.max()` to get the maximum value. Use `Array.prototype.map()` to map each element to the value returned by `fn`, `Math.max()` to get the maximum value.
```js ```js
const maxBy = (arr, fn) => Math.max(...arr.map(typeof fn === 'function' ? fn : val => val[fn])); const maxBy = (arr, fn) => Math.max(...arr.map(typeof fn === 'function' ? fn : val => val[fn]));

View File

@ -3,8 +3,8 @@
Returns the `n` maximum elements from the provided array. Returns the `n` maximum elements from the provided array.
If `n` is greater than or equal to the provided array's length, then return the original array (sorted in descending order). If `n` is greater than or equal to the provided array's length, then return the original array (sorted in descending order).
Use `Array.sort()` combined with the spread operator (`...`) to create a shallow clone of the array and sort it in descending order. Use `Array.prototype.sort()` combined with the spread operator (`...`) to create a shallow clone of the array and sort it in descending order.
Use `Array.slice()` to get the specified number of elements. Use `Array.prototype.slice()` to get the specified number of elements.
Omit the second argument, `n`, to get a one-element array. Omit the second argument, `n`, to get a one-element array.
```js ```js

Some files were not shown because too many files have changed in this diff Show More