typestar

Minimum by key in TypeScript

Finds the smallest item by a computed value, returning undefined for an empty array.

function minBy<T>(items: T[], keyFn: (item: T) => number): T | undefined {
  let best: T | undefined;
  let bestKey = Infinity;
  for (const item of items) {
    const key = keyFn(item);
    if (key < bestKey) {
      best = item;
      bestKey = key;
    }
  }
  return best;
}

Keywords and builtins used here

The run, in numbers

Lines
12
Characters to type
244
Tokens
76
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 43 seconds.

Type this snippet

Step 6 of 11 in Generic helpers, step 14 of 20 in Generics.

← Previous Next →