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.

JavascriptData Integrity

Code

javascriptsnippet
18 lines
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);
}

What the code does

The working surface is the functions takeWhile and dropWhile — everything else is wiring.

The structure is a loop within a loop: for (const item of items) outside, while (index < items.length && predicate(items[index])) index += 1; inside. A guard precedes the TypeError: bad state stops the flow there instead of continuing.

What to watch for

  • The guard typeof predicate !== "function" short-circuits the flow with an early throw when its condition holds.

Applying it

Entry signature: export function takeWhile(items, predicate)

The surface worth importing is takeWhile; the helpers around it are private to the snippet.

Statements that matter

if (typeof predicate !== "function") throw new TypeError("predicate must be a function");
if (!Array.isArray(items)) throw new TypeError("items must be an array");
while (index < items.length && predicate(items[index])) index += 1;

Interactive Tools for This Topic

FAQ

Does the code validate its input?
The code refuses to continue: `TypeError` is thrown while the state is still recoverable.
Which packages does this snippet need?
None. Every symbol the code uses resolves inside the standard library. The file defines `takeWhile`, `dropWhile` at load time.