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.prototype.slice() to drop the last element of the array until the returned value from the function is true. Returns the remaining elements.
const dropRightWhile = (arr, func) => { - while (arr.length > 0 && !func(arr[arr.length - 1])) arr = arr.slice(0, -1); - return arr; + let rightIndex = arr.length; + while (rightIndex-- && !func(arr[rightIndex])); + return arr.slice(0, rightIndex + 1); };
dropRightWhile([1, 2, 3, 4], n => n < 3); // [1, 2]
Removes elements in an array until the passed function returns true. Returns the remaining elements in the array.
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.
const dropWhile = (arr, func) => { diff --git a/snippets/checkProp.md b/snippets/checkProp.md index 86a412cee..391d872d6 100644 --- a/snippets/checkProp.md +++ b/snippets/checkProp.md @@ -19,6 +19,7 @@ const checkProp = (predicate, prop) => obj => !!predicate(obj[prop]); + const lengthIs4 = checkProp(l => l === 4, 'length'); lengthIs4([]); // false lengthIs4([1,2,3,4]); // true diff --git a/test/_30s.js b/test/_30s.js index 1be8796e9..4151e82bd 100644 --- a/test/_30s.js +++ b/test/_30s.js @@ -279,8 +279,9 @@ const distance = (x0, y0, x1, y1) => Math.hypot(x1 - x0, y1 - y0); const drop = (arr, n = 1) => arr.slice(n); const dropRight = (arr, n = 1) => arr.slice(0, -n); const dropRightWhile = (arr, func) => { - while (arr.length > 0 && !func(arr[arr.length - 1])) arr = arr.slice(0, -1); - return arr; + let rightIndex = arr.length; + while (rightIndex-- && !func(arr[rightIndex])); + return arr.slice(0, rightIndex + 1); }; const dropWhile = (arr, func) => { while (arr.length > 0 && !func(arr[0])) arr = arr.slice(1);