Skip to content

Getting Started

The Sort module provides schema-driven, multi-field sorting for Zod-typed data. It mirrors the architecture of the Filter module — define a Zod schema, provide compare functions, and let the library discover sortable fields automatically.

Here’s an interactive example:

nameagescore
Alice3088
Bob2595
Charlie3572
Diana2891
Eve3285
Frank2278
Grace2793
Henry4067
  1. Install the core package using your favorite package manager:

    Terminal window
    pnpm add @fn-sphere/core
  2. If not installed, add zod:

    Terminal window
    pnpm add zod
  3. Define your data schema with Zod:

    import { z } from "zod";
    const schema = z.object({
    name: z.string(),
    age: z.number(),
    });
  4. Create a sorter sphere and sort your data:

    import { createSorterSphere, presetSort } from "@fn-sphere/core";
    const sphere = createSorterSphere(schema, presetSort);
    // Discover which fields are sortable
    const fields = sphere.findSortableField();
    const ageField = fields.find((f) => f.path[0] === "age")!;
    const sortAgeFn = ageField.sortFnList[0]!;
    // Build a sort rule (multi-field supported)
    const rule = [sphere.getSortRule(ageField, sortAgeFn, "desc")];
    // Sort data (non-mutating — returns a new array)
    const sorted = sphere.sortData(users, rule);
    // Or get a reusable comparator
    const cmp = sphere.getSortComparator(rule);
    [...users].sort(cmp);

The built-in presetSort provides a generic compare function that handles string, number, boolean, Date, and enum fields out of the box.

import { presetSort } from "@fn-sphere/core";
const sphere = createSorterSphere(schema, presetSort);