Functional Weave
Code in TypeScript

collections.sort-by

Stably sort records by one key, ascending or descending, with a total order across mixed types.

1.0.0 · published 2026-10-03 by charlie · Anterra

Pinned by 21 tests, run in TypeScript, Python and Rust.

What it does

The sort is stable: records that tie on the key come out in the order they went in, in BOTH directions. Descending negates the comparison rather than reversing the list, so the tied block is not silently flipped - that is what makes sorting by one column and then another compose into the multi-column sort a user expects.

The total order for mixed values is: booleans, then numbers, then strings, and absent values last. Absent values sink to the bottom in both directions, because 'the rows we know nothing about' belong at the end of a descending table as much as an ascending one; reversing them would put the empty rows first, which no one has ever wanted.

For example

  • sortBy(records ×3, n, asc) → ×3 ascending by a string key
  • sortBy(records ×3, n, desc) → ×3 descending by a string key
  • sortBy(records ×3, s, asc) → ×3 ascending by a number key

The function

The same function in TypeScript, Python and Rust, pinned by the same tests. Pick your language; the choice follows you around the registry.

export function sortBy(records: readonly Readonly<Record<string, unknown>>[], key: string, direction: SortDirection): readonly Readonly<Record<string, unknown>>[]
recordsrecord[]open JSON-ish maps; shapes may differ between records
keystringthe field to order by
directionSortDirection
returnsrecord[]a new list; the input is never reordered in place

The type it declares, generated into your project

export type SortDirection = "asc" | "desc";

Your code names it in one line, in the file that uses it

import { sortBy } from "#fune/collections.sort-by@^1";
impl/typescript.ts · 100 lines · open · raw
import { type SortDirection } from "./collections_sort_by_types.ts";

/** An open record, the manifest's `record`: a JSON-ish map whose shape is not known ahead of time. */
type SortableRecord = Readonly<Record<string, unknown>>;

// The type ranks that give mixed values a total order. Absent sorts last in
// both directions, so it is ranked above every present value and then excluded
// from the direction flip below.
const RANK_BOOL = 0;
const RANK_NUMBER = 1;
const RANK_STRING = 2;
const RANK_ABSENT = 3;

function rankOf(value: unknown, key: string): number {
  // Absent and null are the same thing: a document that omits a field and one
  // that nulls it mean the same to every reader.
  if (value === undefined || value === null) return RANK_ABSENT;
  if (typeof value === "boolean") return RANK_BOOL;
  if (typeof value === "number") return RANK_NUMBER;
  if (typeof value === "string") return RANK_STRING;
  throw new TypeError(`cannot sort by the list or map at "${key}"`);
}

/**
 * Compare two strings by Unicode code point.
 *
 * JavaScript's `<` compares UTF-16 code units, while Python and Rust compare
 * code points; they disagree above U+FFFF. Spelling the comparison out makes
 * the order identical in all three languages for every string, not just ASCII.
 */
function compareStrings(a: string, b: string): number {
  const ca = Array.from(a);
  const cb = Array.from(b);
  const shared = Math.min(ca.length, cb.length);
  for (let i = 0; i < shared; i++) {
    const x = ca[i].codePointAt(0) as number;
    const y = cb[i].codePointAt(0) as number;
    if (x !== y) return x < y ? -1 : 1;
  }
  return ca.length === cb.length ? 0 : ca.length < cb.length ? -1 : 1;
}

/**
 * Stably sort `records` by `key`, ascending or descending.
 *
 * Ties keep their input order in both directions, which is what lets a user
 * sort by one column and then another and get the multi-column sort they
 * expect rather than a reshuffle.
 */
export function sortBy(
  records: readonly SortableRecord[],
  key: string,
  direction: SortDirection = "asc",
): readonly SortableRecord[] {
  if (!Array.isArray(records)) {
    throw new TypeError("sortBy needs a list of records");
  }
  if (typeof key !== "string" || key.length === 0) {
    throw new TypeError("sortBy needs a non-empty key name");
  }
  if (direction !== "asc" && direction !== "desc") {
    throw new RangeError(`direction must be "asc" or "desc", received "${direction}"`);
  }

  // Rank every record up front. Raising mid-comparison would make the error
  // depend on which comparisons this engine's sort happened to perform.
  const ranks = records.map((record) =>
    rankOf(record === null || record === undefined ? undefined : record[key], key),
  );
  const sign = direction === "desc" ? -1 : 1;

  const order = records.map((record, index) => ({ record, index }));
  order.sort((a, b) => {
    const ra = ranks[a.index];
    const rb = ranks[b.index];
    // Absent values sink to the bottom whichever way the sort runs: nobody
    // wants the rows they know nothing about at the top of a descending table.
    if (ra === RANK_ABSENT || rb === RANK_ABSENT) {
      if (ra === rb) return 0;
      return ra === RANK_ABSENT ? 1 : -1;
    }
    let base: number;
    if (ra !== rb) {
      base = ra < rb ? -1 : 1;
    } else if (ra === RANK_STRING) {
      base = compareStrings(a.record[key] as string, b.record[key] as string);
    } else if (ra === RANK_NUMBER) {
      const x = a.record[key] as number;
      const y = b.record[key] as number;
      base = x < y ? -1 : x > y ? 1 : 0;
    } else {
      const x = a.record[key] as boolean;
      const y = b.record[key] as boolean;
      base = x === y ? 0 : x ? 1 : -1;
    }
    return base * sign;
  });

  return order.map((entry) => entry.record);
}

Install

fune build

With that line in your source, in a TypeScript project (language typescript in fune.project), fune build resolves it and nothing else, pins them in fune.lock, downloads only the TypeScript package of each, and builds the code above into your project’s .fune/build, one readable file per capability with a header linking back here. Or pin a range in fune.project and build in one step:

fune add collections.sort-by
Download for TypeScript collections.sort-by-1.0.0-typescript.fune · 12,597 bytes sha256 12a88a8eacda51376bb03c8230cce752964112541c36448b86b487dccb091fea

The manifest, vectors and README with only the TypeScript implementation. Install it without the registry with fune add ./collections.sort-by-1.0.0-typescript.fune, or fetch it from a terminal with fune pull collections.sort-by@1.0.0:typescript.

The whole function, every language, is one file too: collections.sort-by-1.0.0.fune, 19,865 bytes, sha256 64f59dd149f5eee9c1e84e5a62ff365767cda76a85825b539a3a053a40a080c6. It installs into a project of any language.

Customise it in your app

The seams this capability offers. Put a marker directly above a function of your own and fune build wires it into the built code; the package on the registry is not changed, the built file’s header lists it under CUSTOMISED, and fune hooks lists every hook in the project. How hooks work.

before — your function gets the arguments and returns them, changed or not, or throws to refuse the call.

// fune: before collections.sort-by

after — your function gets the result and the arguments, and returns the final result.

// fune: after collections.sort-by

replace — it requires no other capability, so there is no dependency to replace.

step — your function runs at a numbered point inside the function’s body, receives the in-scope values it names as parameters, and may return replacements. List the points with fune show collections.sort-by --steps.

// fune: step collections.sort-by after <n|label>

Tests

A version published now needs at least 8 tests for every function, and one that expects the error for each function that throws; the registry refuses it otherwise. fune verify --all runs each case in TypeScript, Python and Rust, and a project runs them again with fune verify. This page lists the cases; it does not run them. The exact JSON is vectors.json.

CaseArgumentsExpected
ascending by a string key records ×3, n, asc → ×3
descending by a string key records ×3, n, desc → ×3
ascending by a number key records ×3, s, asc → ×3
descending by a number key records ×3, s, desc → ×3
ties keep their input order ascending records ×4, s, asc → ×4
ties keep their input order descending too: the tied block is not flipped records ×4, s, desc → ×4
nulls and missing keys sort last ascending, keeping their own order records ×4, s, asc → ×4
nulls stay last descending: the rows we know nothing about never come first records ×4, s, desc → ×4
a list of nothing but absent values comes back in input order records ×3, s, asc → ×3
an empty list sorts to an empty list , s, asc →
Show the other 11 tests
CaseArgumentsExpected
a single record is already sorted, in either direction records ×1, s, desc → ×1
mixed types have one total order ascending: booleans, then numbers, then strings records ×6, v, asc → ×6
mixed types reverse cleanly descending records ×6, v, desc → ×6
integers and fractions interleave by value, not by type records ×4, v, asc → ×4
strings compare by code point, so capitals sort before lowercase records ×4, v, asc → ×4
a prefix sorts before the longer string, and accented letters sort after ASCII records ×4, v, asc → ×4
records with different shapes sort on the one field they share records ×3, n, asc → ×3
an unknown direction is an error, not a silent ascending sort records ×1, s, ascending → error: direction must be "asc" or "desc"
a list at the sort key has no defensible order records ×2, s, asc → error: list or map
a map at the sort key has no defensible order records ×2, s, asc → error: list or map
an empty key name is a caller bug records ×1, , asc → error: non-empty key name

More from the author

A missing key and a null value are the same thing and both sort last.

Strings compare by Unicode code point, spelled out rather than inherited: JavaScript's < compares UTF-16 code units and disagrees with Python and Rust above U+FFFF. Comparison is case-sensitive, so 'Zebra' sorts before 'apple'; lowercase the key first if you want a case-insensitive sort.

A list or a map at the sort key is an error, and it is detected in one pass before sorting starts. Discovering it mid-comparison would make the error depend on which comparisons that language's sort happened to perform.

Files

PathBytes
README.md1,268
impl/python.py3,315
impl/rust.rs3,698
impl/typescript.ts3,794
vectors.json4,914