diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 000000000..940c318b4 --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,20 @@ + + + + +## Description + +**Resolves** #(issue number) + +## Types of changes +- [ ] Bug fix (non-breaking change which fixes an issue) +- [ ] New feature (non-breaking change which adds functionality) +- [ ] Breaking change (fix or feature that would cause existing functionality to change) + +## Checklist: + +- [ ] My code follows the code style of this project. +- [ ] My change requires a change to the documentation. +- [ ] I have updated the documentation accordingly. +- [ ] I have checked that there isn't any PR doing the same +- [ ] I have read the **CONTRIBUTING** document. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 4b1164232..ac39ceccc 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -24,7 +24,7 @@ Here's what you can do to help: - Follow snippet descriptions with an empty line. - **Snippet code** must be enclosed inside ` ```js ` and ` ``` `. - Remember to start your snippet's code on a new line below the opening backticks. - - Use ES6 notation to define your function. For example `const myFunction = arg1, arg2 => { }`. + - Use ES6 notation to define your function. For example `const myFunction = ( arg1, arg2 ) => { }`. - Try to keep your snippets' code short and to the point. Use modern techniques and features. Make sure to test your code before submitting. - All snippets must be followed by one (more if necessary) test case after the code, on a new line, in the form of a comment, along with the expected output. The syntax for this is `myFunction('testInput') -> 'testOutput'`. Use multiline comments only if necessary. - Try to make your function name unique, so that it does not conflict with existing snippets. @@ -57,7 +57,7 @@ Here's what you can do to help: - 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. - 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. - Always use soft tabs (2 spaces), never hard tabs. - Omit curly braces (`{` and `}`) whenever possible. diff --git a/README.md b/README.md index c4a6765d3..2a7f9e566 100644 --- a/README.md +++ b/README.md @@ -17,8 +17,10 @@ * [`countOccurrences`](#countoccurrences) * [`deepFlatten`](#deepflatten) * [`difference`](#difference) +* [`differenceWith`](#differencewith) * [`distinctValuesOfArray`](#distinctvaluesofarray) * [`dropElements`](#dropelements) +* [`dropRight`](#dropright) * [`everyNth`](#everynth) * [`filterNonUnique`](#filternonunique) * [`flatten`](#flatten) @@ -34,6 +36,8 @@ * [`nthElement`](#nthelement) * [`pick`](#pick) * [`pull`](#pull) +* [`pullAll`](#pullall) +* [`pullAtIndex`](#pullatindex) * [`remove`](#remove) * [`sample`](#sample) * [`shuffle`](#shuffle) @@ -103,6 +107,7 @@ * [`cleanObj`](#cleanobj) * [`objectFromPairs`](#objectfrompairs) * [`objectToPairs`](#objecttopairs) +* [`select`](#select) * [`shallowClone`](#shallowclone) * [`truthCheckCollection`](#truthcheckcollection) @@ -110,6 +115,7 @@ * [`anagrams`](#anagrams) * [`capitalize`](#capitalize) * [`capitalizeEveryWord`](#capitalizeeveryword) +* [`countVowels`](#countvowels) * [`escapeRegExp`](#escaperegexp) * [`fromCamelCase`](#fromcamelcase) * [`reverseString`](#reversestring) @@ -234,6 +240,19 @@ const difference = (a, b) => { const s = new Set(b); return a.filter(x => !s.has [⬆ back to top](#table-of-contents) +### differenceWith + +Filters out all values from an array for which the comparator function does not return `true`. + +Use `Array.filter()` and `Array.find()` to find the appropriate values. + +```js +const differenceWith = (arr, val, comp) => arr.filter(a => !val.find(b => comp(a, b))) +// differenceWith([1, 1.2, 1.5, 3], [1.9, 3], (a,b) => Math.round(a) == Math.round(b)) -> [1, 1.2] +``` + +[⬆ back to top](#table-of-contents) + ### distinctValuesOfArray Returns all the distinct values of an array. @@ -251,12 +270,12 @@ const distinctValuesOfArray = arr => [...new Set(arr)]; Removes elements in an array until the passed function returns `true`. Returns the remaining elements in the array. -Loop through the array, using `Array.shift()` to drop the first element of the array until the returned value from the function is `true`. +Loop through the array, using `Array.slice()` to drop the first element of the array until the returned value from the function is `true`. Returns the remaining elements. ```js const dropElements = (arr, func) => { - while (arr.length > 0 && !func(arr[0])) arr.shift(); + while (arr.length > 0 && !func(arr[0])) arr = arr.slice(1); return arr; }; // dropElements([1, 2, 3, 4], n => n >= 3) -> [3,4] @@ -264,6 +283,21 @@ const dropElements = (arr, func) => { [⬆ back to top](#table-of-contents) +### dropRight + +Returns a new array with `n` elements removed from the right + +Check if `n` is shorter than the given array and use `Array.slice()` to slice it accordingly or return an empty array. + +```js +const dropRight = (arr, n = 1) => n < arr.length ? arr.slice(0, arr.length - n) : [] +//dropRight([1,2,3]) -> [1,2] +//dropRight([1,2,3], 2) -> [1] +//dropRight([1,2,3], 42) -> [] +``` + +[⬆ back to top](#table-of-contents) + ### everyNth Returns every nth element in an array. @@ -366,15 +400,16 @@ const initial = arr => arr.slice(0, -1); ### initializeArrayWithRange -Initializes an array containing the numbers in the specified range. +Initializes an array containing the numbers in the specified range where `start` and `end` are inclusive. -Use `Array(end-start)` to create an array of the desired length, `Array.map()` to fill with the desired values in a range. +Use `Array((end + 1) - start)` to create an array of the desired length, `Array.map()` to fill with the desired values in a range. You can omit `start` to use a default value of `0`. ```js -const initializeArrayWithRange = (end, start = 0) => - Array.from({ length: end - start }).map((v, i) => i + start); -// initializeArrayWithRange(5) -> [0,1,2,3,4] +const initializeArrayWithRange = (end, start = 0) => + Array.from({ length: (end + 1) - start }).map((v, i) => i + start); +// initializeArrayWithRange(5) -> [0,1,2,3,4,5] +// initializeArrayWithRange(7, 3) -> [3,4,5,6,7] ``` [⬆ back to top](#table-of-contents) @@ -473,6 +508,8 @@ Mutates the original array to filter out the values specified. Use `Array.filter()` and `Array.includes()` to pull out the values that are not needed. Use `Array.length = 0` to mutate the passed in array by resetting it's length to zero and `Array.push()` to re-populate it with only the pulled values. +_(For a snippet that does not mutate the original array see [`without`](#without))_ + ```js const pull = (arr, ...args) => { let pulled = arr.filter((v, i) => !args.includes(v)); @@ -485,6 +522,52 @@ const pull = (arr, ...args) => { [⬆ back to top](#table-of-contents) +### pullAll + +Mutates the original array to filter out the values specified (accepts an array of values). + +Use `Array.filter()` and `Array.includes()` to pull out the values that are not needed. +Use `Array.length = 0` to mutate the passed in array by resetting it's length to zero and `Array.push()` to re-populate it with only the pulled values. + +```js +const pullAll = (arr, pullArr) => { + let pulled = arr.filter((v, i) => !pullArr.includes(v)); + arr.length = 0; pulled.forEach(v => arr.push(v)); +} +// let myArray = ['a', 'b', 'c', 'a', 'b', 'c']; +// pullAll(myArray, ['a', 'c']); +// console.log(myArray) -> [ 'b', 'b' ] +``` + +[⬆ back to top](#table-of-contents) + +### pullAtIndex + +Mutates the original array to filter out the values at the specified indexes. + +Use `Array.filter()` and `Array.includes()` to pull out the values that are not needed. +Use `Array.length = 0` to mutate the passed in array by resetting it's length to zero and `Array.push()` to re-populate it with only the pulled values. +Use `Array.push()` to keep track of pulled values + +```js +const pullAtIndex = (arr, pullArr) => { + let removed = []; + let pulled = arr.map((v, i) => pullArr.includes(i) ? removed.push(v) : v) + .filter((v, i) => !pullArr.includes(i)) + arr.length = 0; + pulled.forEach(v => arr.push(v)); + return removed; +} + +// let myArray = ['a', 'b', 'c', 'd']; +// let pulled = pullAtIndex(myArray, [1, 3]); + +// console.log(myArray); -> [ 'a', 'c' ] +// console.log(pulled); -> [ 'b', 'd' ] +``` + +[⬆ back to top](#table-of-contents) + ### remove Removes elements from an array for which the given function returns `false`. @@ -620,6 +703,8 @@ Filters out the elements of an array, that have one of the specified values. Use `Array.filter()` to create an array excluding(using `!Array.includes()`) all given values. +_(For a snippet that mutates the original array see [`pull`](#pull))_ + ```js const without = (arr, ...args) => arr.filter(v => !args.includes(v)); // without([2, 1, 2, 3], 1, 2) -> [3] @@ -657,7 +742,7 @@ Use `scrollY`, `scrollHeight` and `clientHeight` to determine if the bottom of t ```js const bottomVisible = () => - document.documentElement.clientHeight + window.scrollY >= document.documentElement.scrollHeight || document.documentElement.clientHeight; + document.documentElement.clientHeight + window.scrollY >= (document.documentElement.scrollHeight || document.documentElement.clientHeight); // bottomVisible() -> true ``` @@ -1143,7 +1228,7 @@ Return the number at the midpoint if `length` is odd, otherwise the average of t ```js const median = arr => { - const mid = Math.floor(arr.length / 2), nums = arr.sort((a, b) => a - b); + const mid = Math.floor(arr.length / 2), nums = [...arr].sort((a, b) => a - b); return arr.length % 2 !== 0 ? nums[mid] : (nums[mid - 1] + nums[mid]) / 2; }; // median([5,6,50,1,-5]) -> 5 @@ -1372,6 +1457,22 @@ const objectToPairs = obj => Object.keys(obj).map(k => [k, obj[k]]); [⬆ back to top](#table-of-contents) +### select + +Retrieve a property that indicated by the selector from object. + +If property not exists returns `undefined`. + +```js +const select = (from, selector) => + selector.split('.').reduce((prev, cur) => prev && prev[cur], from); + +// const obj = {selector: {to: {val: 'val to select'}}}; +// select(obj, 'selector.to.val'); -> 'val to select' +``` + +[⬆ back to top](#table-of-contents) + ### shallowClone Creates a shallow clone of an object. @@ -1452,6 +1553,20 @@ const capitalizeEveryWord = str => str.replace(/\b[a-z]/g, char => char.toUpperC [⬆ back to top](#table-of-contents) +### countVowels + +Retuns `number` of vowels in provided string. + +Use a regular expression to count number of vowels `(A, E, I, O, U)` in a `string`. + +```js +const countVowels = str => (str.match(/[aeiou]/ig) || []).length; +// countVowels('foobar') -> 3 +// countVowels('gym') -> 0 +``` + +[⬆ back to top](#table-of-contents) + ### escapeRegExp Escapes a string to use in a regular expression. @@ -1487,11 +1602,11 @@ const fromCamelCase = (str, separator = '_') => Reverses a string. -Use array destructuring and `Array.reverse()` to reverse the order of the characters in the string. +Use `split('')` and `Array.reverse()` to reverse the order of the characters in the string. Combine characters to get a string using `join('')`. ```js -const reverseString = str => [...str].reverse().join(''); +const reverseString = str => str.split('').reverse().join(''); // reverseString('foobar') -> 'raboof' ``` diff --git a/docs/index.html b/docs/index.html index 20531f201..44d8db8eb 100644 --- a/docs/index.html +++ b/docs/index.html @@ -31,7 +31,7 @@ -
+

differenceWith

+

Filters out all values from an array for which the comparator function does not return true.

+

Use Array.filter() and Array.find() to find the appropriate values.

+
const differenceWith = (arr, val, comp) => arr.filter(a => !val.find(b => comp(a, b)))
+// differenceWith([1, 1.2, 1.5, 3], [1.9, 3], (a,b) => Math.round(a) == Math.round(b)) -> [1, 1.2]
+

distinctValuesOfArray

Returns all the distinct values of an array.

Use ES6 Set and the ...rest operator to discard all duplicated values.

@@ -220,14 +232,22 @@ Recursively flatten each element that is an array.


dropElements

Removes elements in an array until the passed function returns true. Returns the remaining elements in the array.

-

Loop through the array, using Array.shift() to drop the first element of the array until the returned value from the function is true. +

Loop through the array, using Array.slice() to drop the first element of the array until the returned value from the function is true. Returns the remaining elements.

const dropElements = (arr, func) => {
-  while (arr.length > 0 && !func(arr[0])) arr.shift();
+  while (arr.length > 0 && !func(arr[0])) arr = arr.slice(1);
   return arr;
 };
 // dropElements([1, 2, 3, 4], n => n >= 3) -> [3,4]
 
+

dropRight

+

Returns a new array with n elements removed from the right

+

Check if n is shorter than the given array and use Array.slice() to slice it accordingly or return an empty array.

+
const dropRight = (arr, n = 1) => n < arr.length ? arr.slice(0, arr.length - n) : []
+//dropRight([1,2,3]) -> [1,2]
+//dropRight([1,2,3], 2) -> [1]
+//dropRight([1,2,3], 42) -> []
+

everyNth

Returns every nth element in an array.

Use Array.filter() to create a new array that contains every nth element of a given array.

@@ -280,12 +300,13 @@ Use Array.reduce() to create an object, where the keys are produced // initial([1,2,3]) -> [1,2]

initializeArrayWithRange

-

Initializes an array containing the numbers in the specified range.

-

Use Array(end-start) to create an array of the desired length, Array.map() to fill with the desired values in a range. +

Initializes an array containing the numbers in the specified range where start and end are inclusive.

+

Use Array((end + 1) - start) to create an array of the desired length, Array.map() to fill with the desired values in a range. You can omit start to use a default value of 0.

-
const initializeArrayWithRange = (end, start = 0) =>
-  Array.from({ length: end - start }).map((v, i) => i + start);
-// initializeArrayWithRange(5) -> [0,1,2,3,4]
+
const initializeArrayWithRange = (end, start = 0) => 
+  Array.from({ length: (end + 1) - start }).map((v, i) => i + start);
+// initializeArrayWithRange(5) -> [0,1,2,3,4,5]
+// initializeArrayWithRange(7, 3) -> [3,4,5,6,7]
 

initializeArrayWithValues

Initializes and fills an array with the specified values.

@@ -336,6 +357,7 @@ Omit the second argument, n, to get the first element of the array.

Mutates the original array to filter out the values specified.

Use Array.filter() and Array.includes() to pull out the values that are not needed. Use Array.length = 0 to mutate the passed in array by resetting it's length to zero and Array.push() to re-populate it with only the pulled values.

+

(For a snippet that does not mutate the original array see without)

const pull = (arr, ...args) => {
   let pulled = arr.filter((v, i) => !args.includes(v));
   arr.length = 0; pulled.forEach(v => arr.push(v));
@@ -344,6 +366,38 @@ Use Array.length = 0 to mutate the passed in array by resetting it'
 // pull(myArray, 'a', 'c');
 // console.log(myArray) -> [ 'b', 'b' ]
 
+

pullAll

+

Mutates the original array to filter out the values specified (accepts an array of values).

+

Use Array.filter() and Array.includes() to pull out the values that are not needed. +Use Array.length = 0 to mutate the passed in array by resetting it's length to zero and Array.push() to re-populate it with only the pulled values.

+
const pullAll = (arr, pullArr) => {
+  let pulled = arr.filter((v, i) => !pullArr.includes(v));
+  arr.length = 0; pulled.forEach(v => arr.push(v));
+}
+// let myArray = ['a', 'b', 'c', 'a', 'b', 'c'];
+// pullAll(myArray, ['a', 'c']);
+// console.log(myArray) -> [ 'b', 'b' ]
+
+

pullAtIndex

+

Mutates the original array to filter out the values at the specified indexes.

+

Use Array.filter() and Array.includes() to pull out the values that are not needed. +Use Array.length = 0 to mutate the passed in array by resetting it's length to zero and Array.push() to re-populate it with only the pulled values. +Use Array.push() to keep track of pulled values

+
const pullAtIndex = (arr, pullArr) => {
+  let removed = [];
+  let pulled = arr.map((v, i) => pullArr.includes(i) ? removed.push(v) : v)
+                  .filter((v, i) => !pullArr.includes(i))
+  arr.length = 0; 
+  pulled.forEach(v => arr.push(v));
+  return removed;
+}
+
+// let myArray = ['a', 'b', 'c', 'd'];
+// let pulled = pullAtIndex(myArray, [1, 3]);
+
+// console.log(myArray); -> [ 'a', 'c' ]
+// console.log(pulled); -> [ 'b', 'd' ]
+

remove

Removes elements from an array for which the given function returns false.

Use Array.filter() to find array elements that return truthy values and Array.reduce() to remove elements using Array.splice(). @@ -413,6 +467,7 @@ This method also works with strings.


without

Filters out the elements of an array, that have one of the specified values.

Use Array.filter() to create an array excluding(using !Array.includes()) all given values.

+

(For a snippet that mutates the original array see pull)

const without = (arr, ...args) => arr.filter(v => !args.includes(v));
 // without([2, 1, 2, 3], 1, 2) -> [3]
 
@@ -435,7 +490,7 @@ If lengths of the argument-arrays vary, undefined is used where no

Returns true if the bottom of the page is visible, false otherwise.

Use scrollY, scrollHeight and clientHeight to determine if the bottom of the page is visible.

const bottomVisible = () =>
-  document.documentElement.clientHeight + window.scrollY >= document.documentElement.scrollHeight || document.documentElement.clientHeight;
+  document.documentElement.clientHeight + window.scrollY >= (document.documentElement.scrollHeight || document.documentElement.clientHeight);
 // bottomVisible() -> true
 

currentURL

@@ -710,7 +765,7 @@ The GCD formula uses recursion.

Find the middle of the array, use Array.sort() to sort the values. Return the number at the midpoint if length is odd, otherwise the average of the two middle numbers.

const median = arr => {
-  const mid = Math.floor(arr.length / 2), nums = arr.sort((a, b) => a - b);
+  const mid = Math.floor(arr.length / 2), nums = [...arr].sort((a, b) => a - b);
   return arr.length % 2 !== 0 ? nums[mid] : (nums[mid - 1] + nums[mid]) / 2;
 };
 // median([5,6,50,1,-5]) -> 5
@@ -844,6 +899,15 @@ Also if you give it a special key (childIndicator) it will search d
 
const objectToPairs = obj => Object.keys(obj).map(k => [k, obj[k]]);
 // objectToPairs({a: 1, b: 2}) -> [['a',1],['b',2]])
 
+

select

+

Retrieve a property that indicated by the selector from object.

+

If property not exists returns undefined.

+
const select = (from, selector) =>
+  selector.split('.').reduce((prev, cur) => prev && prev[cur], from);
+
+// const obj = {selector: {to: {val: 'val to select'}}};
+// select(obj, 'selector.to.val'); -> 'val to select'
+

shallowClone

Creates a shallow clone of an object.

Use Object.assign() and an empty object ({}) to create a shallow clone of the original.

@@ -889,6 +953,13 @@ Omit the lowerRest parameter to keep the rest of the string intact,
const capitalizeEveryWord = str => str.replace(/\b[a-z]/g, char => char.toUpperCase());
 // capitalizeEveryWord('hello world!') -> 'Hello World!'
 
+

countVowels

+

Retuns number of vowels in provided string.

+

Use a regular expression to count number of vowels (A, E, I, O, U) in a string.

+
const countVowels = str => (str.match(/[aeiou]/ig) || []).length;
+// countVowels('foobar') -> 3
+// countVowels('gym') -> 0
+

escapeRegExp

Escapes a string to use in a regular expression.

Use replace() to escape special characters.

@@ -908,9 +979,9 @@ Omit the second argument to use a default separator of _.


reverseString

Reverses a string.

-

Use array destructuring and Array.reverse() to reverse the order of the characters in the string. +

Use split('') and Array.reverse() to reverse the order of the characters in the string. Combine characters to get a string using join('').

-
const reverseString = str => [...str].reverse().join('');
+
const reverseString = str => str.split('').reverse().join('');
 // reverseString('foobar') -> 'raboof'
 

sortCharactersInString

diff --git a/snippets/bottomVisible.md b/snippets/bottomVisible.md index 8e655db45..adac44881 100644 --- a/snippets/bottomVisible.md +++ b/snippets/bottomVisible.md @@ -6,6 +6,6 @@ Use `scrollY`, `scrollHeight` and `clientHeight` to determine if the bottom of t ```js const bottomVisible = () => - document.documentElement.clientHeight + window.scrollY >= document.documentElement.scrollHeight || document.documentElement.clientHeight; + document.documentElement.clientHeight + window.scrollY >= (document.documentElement.scrollHeight || document.documentElement.clientHeight); // bottomVisible() -> true ``` diff --git a/snippets/countVowels.md b/snippets/countVowels.md new file mode 100644 index 000000000..bf1f536fc --- /dev/null +++ b/snippets/countVowels.md @@ -0,0 +1,11 @@ +### countVowels + +Retuns `number` of vowels in provided string. + +Use a regular expression to count number of vowels `(A, E, I, O, U)` in a `string`. + +```js +const countVowels = str => (str.match(/[aeiou]/ig) || []).length; +// countVowels('foobar') -> 3 +// countVowels('gym') -> 0 +``` diff --git a/snippets/differenceWith.md b/snippets/differenceWith.md new file mode 100644 index 000000000..ba4aac0ec --- /dev/null +++ b/snippets/differenceWith.md @@ -0,0 +1,10 @@ +### differenceWith + +Filters out all values from an array for which the comparator function does not return `true`. + +Use `Array.filter()` and `Array.find()` to find the appropriate values. + +```js +const differenceWith = (arr, val, comp) => arr.filter(a => !val.find(b => comp(a, b))) +// differenceWith([1, 1.2, 1.5, 3], [1.9, 3], (a,b) => Math.round(a) == Math.round(b)) -> [1, 1.2] +``` diff --git a/snippets/dropElements.md b/snippets/dropElements.md index 34138eb93..adc81d79d 100644 --- a/snippets/dropElements.md +++ b/snippets/dropElements.md @@ -2,12 +2,12 @@ Removes elements in an array until the passed function returns `true`. Returns the remaining elements in the array. -Loop through the array, using `Array.shift()` to drop the first element of the array until the returned value from the function is `true`. +Loop through the array, using `Array.slice()` to drop the first element of the array until the returned value from the function is `true`. Returns the remaining elements. ```js const dropElements = (arr, func) => { - while (arr.length > 0 && !func(arr[0])) arr.shift(); + while (arr.length > 0 && !func(arr[0])) arr = arr.slice(1); return arr; }; // dropElements([1, 2, 3, 4], n => n >= 3) -> [3,4] diff --git a/snippets/dropRight.md b/snippets/dropRight.md new file mode 100644 index 000000000..d1a56d764 --- /dev/null +++ b/snippets/dropRight.md @@ -0,0 +1,12 @@ +### dropRight + +Returns a new array with `n` elements removed from the right + +Check if `n` is shorter than the given array and use `Array.slice()` to slice it accordingly or return an empty array. + +```js +const dropRight = (arr, n = 1) => n < arr.length ? arr.slice(0, arr.length - n) : [] +//dropRight([1,2,3]) -> [1,2] +//dropRight([1,2,3], 2) -> [1] +//dropRight([1,2,3], 42) -> [] +``` diff --git a/snippets/initializeArrayWithRange.md b/snippets/initializeArrayWithRange.md index 75dbc8adf..c3ef5a0a0 100644 --- a/snippets/initializeArrayWithRange.md +++ b/snippets/initializeArrayWithRange.md @@ -1,12 +1,13 @@ ### initializeArrayWithRange -Initializes an array containing the numbers in the specified range. +Initializes an array containing the numbers in the specified range where `start` and `end` are inclusive. -Use `Array(end-start)` to create an array of the desired length, `Array.map()` to fill with the desired values in a range. +Use `Array((end + 1) - start)` to create an array of the desired length, `Array.map()` to fill with the desired values in a range. You can omit `start` to use a default value of `0`. ```js -const initializeArrayWithRange = (end, start = 0) => - Array.from({ length: end - start }).map((v, i) => i + start); -// initializeArrayWithRange(5) -> [0,1,2,3,4] +const initializeArrayWithRange = (end, start = 0) => + Array.from({ length: (end + 1) - start }).map((v, i) => i + start); +// initializeArrayWithRange(5) -> [0,1,2,3,4,5] +// initializeArrayWithRange(7, 3) -> [3,4,5,6,7] ``` diff --git a/snippets/median.md b/snippets/median.md index fd8ca3d7c..c7eea609c 100644 --- a/snippets/median.md +++ b/snippets/median.md @@ -7,7 +7,7 @@ Return the number at the midpoint if `length` is odd, otherwise the average of t ```js const median = arr => { - const mid = Math.floor(arr.length / 2), nums = arr.sort((a, b) => a - b); + const mid = Math.floor(arr.length / 2), nums = [...arr].sort((a, b) => a - b); return arr.length % 2 !== 0 ? nums[mid] : (nums[mid - 1] + nums[mid]) / 2; }; // median([5,6,50,1,-5]) -> 5 diff --git a/snippets/pull.md b/snippets/pull.md index 4913c5082..42efe6c1b 100644 --- a/snippets/pull.md +++ b/snippets/pull.md @@ -5,6 +5,8 @@ Mutates the original array to filter out the values specified. Use `Array.filter()` and `Array.includes()` to pull out the values that are not needed. Use `Array.length = 0` to mutate the passed in array by resetting it's length to zero and `Array.push()` to re-populate it with only the pulled values. +_(For a snippet that does not mutate the original array see [`without`](#without))_ + ```js const pull = (arr, ...args) => { let pulled = arr.filter((v, i) => !args.includes(v)); diff --git a/snippets/pullAll.md b/snippets/pullAll.md new file mode 100644 index 000000000..ab8bf2285 --- /dev/null +++ b/snippets/pullAll.md @@ -0,0 +1,16 @@ +### pullAll + +Mutates the original array to filter out the values specified (accepts an array of values). + +Use `Array.filter()` and `Array.includes()` to pull out the values that are not needed. +Use `Array.length = 0` to mutate the passed in array by resetting it's length to zero and `Array.push()` to re-populate it with only the pulled values. + +```js +const pullAll = (arr, pullArr) => { + let pulled = arr.filter((v, i) => !pullArr.includes(v)); + arr.length = 0; pulled.forEach(v => arr.push(v)); +} +// let myArray = ['a', 'b', 'c', 'a', 'b', 'c']; +// pullAll(myArray, ['a', 'c']); +// console.log(myArray) -> [ 'b', 'b' ] +``` diff --git a/snippets/pullAtIndex.md b/snippets/pullAtIndex.md new file mode 100644 index 000000000..0e0d8cf7f --- /dev/null +++ b/snippets/pullAtIndex.md @@ -0,0 +1,24 @@ +### pullAtIndex + +Mutates the original array to filter out the values at the specified indexes. + +Use `Array.filter()` and `Array.includes()` to pull out the values that are not needed. +Use `Array.length = 0` to mutate the passed in array by resetting it's length to zero and `Array.push()` to re-populate it with only the pulled values. +Use `Array.push()` to keep track of pulled values + +```js +const pullAtIndex = (arr, pullArr) => { + let removed = []; + let pulled = arr.map((v, i) => pullArr.includes(i) ? removed.push(v) : v) + .filter((v, i) => !pullArr.includes(i)) + arr.length = 0; + pulled.forEach(v => arr.push(v)); + return removed; +} + +// let myArray = ['a', 'b', 'c', 'd']; +// let pulled = pullAtIndex(myArray, [1, 3]); + +// console.log(myArray); -> [ 'a', 'c' ] +// console.log(pulled); -> [ 'b', 'd' ] +``` diff --git a/snippets/reverseString.md b/snippets/reverseString.md index a76c506db..5564a5897 100644 --- a/snippets/reverseString.md +++ b/snippets/reverseString.md @@ -2,10 +2,10 @@ Reverses a string. -Use array destructuring and `Array.reverse()` to reverse the order of the characters in the string. +Use `split('')` and `Array.reverse()` to reverse the order of the characters in the string. Combine characters to get a string using `join('')`. ```js -const reverseString = str => [...str].reverse().join(''); +const reverseString = str => str.split('').reverse().join(''); // reverseString('foobar') -> 'raboof' ``` diff --git a/snippets/select.md b/snippets/select.md new file mode 100644 index 000000000..6f60f4d95 --- /dev/null +++ b/snippets/select.md @@ -0,0 +1,13 @@ +### select + +Retrieve a property that indicated by the selector from object. + +If property not exists returns `undefined`. + +```js +const select = (from, selector) => + selector.split('.').reduce((prev, cur) => prev && prev[cur], from); + +// const obj = {selector: {to: {val: 'val to select'}}}; +// select(obj, 'selector.to.val'); -> 'val to select' +``` diff --git a/snippets/without.md b/snippets/without.md index 70f2a20aa..532ec26d9 100644 --- a/snippets/without.md +++ b/snippets/without.md @@ -4,6 +4,8 @@ Filters out the elements of an array, that have one of the specified values. Use `Array.filter()` to create an array excluding(using `!Array.includes()`) all given values. +_(For a snippet that mutates the original array see [`pull`](#pull))_ + ```js const without = (arr, ...args) => arr.filter(v => !args.includes(v)); // without([2, 1, 2, 3], 1, 2) -> [3] diff --git a/static-parts/index-start.html b/static-parts/index-start.html index 09fdb25ac..b988f7928 100644 --- a/static-parts/index-start.html +++ b/static-parts/index-start.html @@ -31,7 +31,7 @@ -
+