Add takeWhile, takeRightWhile

This commit is contained in:
Angelos Chalaris
2018-01-26 12:55:31 +02:00
parent aea334a94a
commit 05d2843450
3 changed files with 38 additions and 0 deletions

View File

@ -0,0 +1,18 @@
### takeRightWhile
Removes elements from the end of an array until the passed function returns `true`. Returns the removed elements.
Loop through the array, using a `for...of` loop over `Array.keys()` until the returned value from the function is `true`.
Return the removed elements, using `Array.reverse()` and `Array.slice()`.
```js
const takeRightWhile = (arr, func) => {
for (let i of arr.reverse().keys())
if (func(arr[i])) return arr.reverse().slice(arr.length - i,arr.length);
return arr;
};
```
```js
takeRightWhile([1, 2, 3, 4], n => n < 3); // [3, 4]
```