Update drop, add dropWhile, dropRightWhile

This commit is contained in:
Angelos Chalaris
2018-01-26 12:23:18 +02:00
parent 49b1fc7947
commit aea334a94a
14 changed files with 65 additions and 31 deletions

15
snippets/drop.md Normal file
View 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); // []
```

View 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]
```

View File

@ -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]
```