Update drop, add dropWhile, dropRightWhile
This commit is contained in:
15
snippets/drop.md
Normal file
15
snippets/drop.md
Normal file
@ -0,0 +1,15 @@
|
||||
### drop
|
||||
|
||||
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.
|
||||
|
||||
```js
|
||||
const drop = (arr, n = 1) => arr.slice(n);
|
||||
```
|
||||
|
||||
```js
|
||||
drop([1, 2, 3]); // [2,3]
|
||||
drop([1, 2, 3], 2); // [3]
|
||||
drop([1, 2, 3], 42); // []
|
||||
```
|
||||
17
snippets/dropRightWhile.md
Normal file
17
snippets/dropRightWhile.md
Normal file
@ -0,0 +1,17 @@
|
||||
### dropRightWhile
|
||||
|
||||
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`.
|
||||
Returns the remaining elements.
|
||||
|
||||
```js
|
||||
const dropRightWhile = (arr, func) => {
|
||||
while (arr.length > 0 && !func(arr[arr.length-1])) arr = arr.slice(0, -1);
|
||||
return arr;
|
||||
};
|
||||
```
|
||||
|
||||
```js
|
||||
dropRightWhile([1, 2, 3, 4], n => n < 3); // [1, 2]
|
||||
```
|
||||
@ -1,4 +1,4 @@
|
||||
### dropElements
|
||||
### dropWhile
|
||||
|
||||
Removes elements in an array until the passed function returns `true`. Returns the remaining elements in the array.
|
||||
|
||||
@ -6,12 +6,12 @@ Loop through the array, using `Array.slice()` to drop the first element of the a
|
||||
Returns the remaining elements.
|
||||
|
||||
```js
|
||||
const dropElements = (arr, func) => {
|
||||
const dropWhile = (arr, func) => {
|
||||
while (arr.length > 0 && !func(arr[0])) arr = arr.slice(1);
|
||||
return arr;
|
||||
};
|
||||
```
|
||||
|
||||
```js
|
||||
dropElements([1, 2, 3, 4], n => n >= 3); // [3,4]
|
||||
dropWhile([1, 2, 3, 4], n => n >= 3); // [3,4]
|
||||
```
|
||||
Reference in New Issue
Block a user