Skip to main content

filterMap

Filters and maps an iterable in a single operation.
it
Iterable<T>
required
The iterable to filter and map
filter
(e: T, i: number) => U | undefined
required
A function that takes an element and its index, and returns the mapped element or undefined if the element should be filtered out
return
U[]
A new array containing the mapped elements that passed the filter

Example

import { filterMap } from "@temelj/iterator";

const numbers = [1, 2, 3, 4, 5];

// Keep only even numbers and double them
const result = filterMap(numbers, (n) => {
  if (n % 2 === 0) {
    return n * 2;
  }
  return undefined;
});

console.log(result); // [4, 8]

// Parse strings, filtering out invalid ones
const strings = ["1", "not a number", "42"];
const parsed = filterMap(strings, (s) => {
  const num = parseInt(s);
  return isNaN(num) ? undefined : num;
});

console.log(parsed); // [1, 42]

partition

Splits an iterable into two arrays based on a predicate.
iterable
Iterable<T>
required
The iterable to partition
predicate
(item: T) => boolean
required
A function that returns true for elements that should go in the first array
return
[T[], T[]]
A tuple of two arrays: [truthyElements, falsyElements]

Example

import { partition } from "@temelj/iterator";

const numbers = [1, 2, 3, 4, 5, 6];
const [even, odd] = partition(numbers, (n) => n % 2 === 0);

console.log(even); // [2, 4, 6]
console.log(odd);  // [1, 3, 5]

// Partition objects
const users = [
  { name: "Alice", active: true },
  { name: "Bob", active: false },
  { name: "Charlie", active: true },
];

const [active, inactive] = partition(users, (u) => u.active);
console.log(active);   // [{ name: "Alice", active: true }, { name: "Charlie", active: true }]
console.log(inactive); // [{ name: "Bob", active: false }]

Build docs developers (and LLMs) love