Take While and Drop While Array Helpers
Implement takeWhile and dropWhile helpers that stop testing after the first failure and never mutate the source array.
Code
export function takeWhile(items, predicate) {
if (!Array.isArray(items)) throw new TypeError("items must be an array");
if (typeof predicate !== "function") throw new TypeError("predicate must be a function");
const result = [];
for (const item of items) {
if (!predicate(item)) break;
result.push(item);
}
return result;
}
export function dropWhile(items, predicate) {
if (!Array.isArray(items)) throw new TypeError("items must be an array");
if (typeof predicate !== "function") throw new TypeError("predicate must be a function");
let index = 0;
while (index < items.length && predicate(items[index])) index += 1;
return items.slice(index);
}Report a problem with this exampleOpens a pre-filled issue on GitHub.