JavaScript Snippet

Partition an Array by a Predicate

Difficulty: Medium

Calling `array.filter(p)` and `array.filter((x) => !p(x))` works but walks the input twice and runs the predicate twice per element, which is wasteful and (for non-pure predicates) plain wrong. A single-pass `partition` returns the matched and unmatched buckets in one go. This snippet covers a clean fold-based implementation, an N-way `partitionBy` for multi-class splits, and a streaming variant that lazily partitions an iterable without materialising the full input.