TypeScript

takeWhile / dropWhile

admin by @admin ADMIN
3h ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Consume or skip leading elements as long as a predicate holds. Useful for parsing prefixed sequences (e.g. all leading whitespace tokens, all unread notifications, etc.).
TypeScript
Raw
export function takeWhile<T>(items: readonly T[], pred: (x: T) => boolean): T[] {
  const out: T[] = [];
  for (const x of items) {
    if (!pred(x)) break;
    out.push(x);
  }
  return out;
}

export function dropWhile<T>(items: readonly T[], pred: (x: T) => boolean): T[] {
  let i = 0;
  while (i < items.length && pred(items[i]!)) i++;
  return items.slice(i);
}

takeWhile([1, 3, 5, 4, 7], n => n % 2 === 1);   // [1, 3, 5]
dropWhile([1, 3, 5, 4, 7], n => n % 2 === 1);   // [4, 7]
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.