id-order-spacing
Minimal, collision-safe ordering for sortable lists.
id-order-spacing is a lightweight utility for managing item order when inserting or moving elements within a sorted array. It calculates stable order values and applies the smallest possible adjustments to avoid collisions—making it ideal for database-backed lists.
Links:
- GitHub: https://github.com/odama626/id-order-spacing
- npm: https://www.npmjs.com/package/@sparkstone/id-order-spacing
What it does
-
Collision-safe inserts
Calculate a new order value when inserting an item at a specific index—or appending to the end. -
Stable move operations
Move items within a list while minimizing changes to surrounding items.
-
Minimal database writes
Only items that require order adjustments are returned, reducing update churn. -
Configurable spacing
Customize spacing behavior using exposed
stepandminimumStepvalues. -
Batch-friendly updates
Includes helpers for batching database writes efficiently.
Installation
pnpm install @sparkstone/id-order-spacing
or
npm install @sparkstone/id-order-spacing
Basic usage
Inserting items
import { calculateInsert } from "@sparkstone/id-order-spacing";
const items = [
{ id: "a", order: 100 },
{ id: "b", order: 200 },
{ id: "c", order: 300 },
];
const newItem = { id: "d", order: 0 };
const result = calculateInsert(items, newItem);
// Insert result.item into the database
await db.create(result.item);
// Apply only the required order updates
for (const [id, order] of result.changes.entries()) {
await db.update(id, { order });
}
Moving items
import {
calculateUpdateFromMove,
batchIterator,
} from "@sparkstone/id-order-spacing";
const result = calculateUpdateFromMove(items, fromIndex, toIndex);
for (const subset of batchIterator(result.changes.entries(), 10)) {
const batch = db.createBatch();
for (const [id, order] of subset) {
batch.update(id, { order });
}
await batch.send();
}
Configuration
Advanced spacing control is available via exported constants:
import { step, minimumStep } from "@sparkstone/id-order-spacing";
console.log(step); // Default spacing step (e.g. 100)
console.log(minimumStep); // Minimum gap before rebalance
These values can also be overridden per operation.
Why it exists
Sortable lists are deceptively tricky when backed by a database—especially when items are frequently reordered. id-order-spacing provides a predictable, low-churn approach to ordering that scales well over time, avoids full-list rebalances, and keeps write operations to a minimum.
It’s designed to be small, explicit, and easy to reason about—whether you’re building task lists, kanban boards, or drag-and-drop UIs.
This remind you of a problem you've been dealing with?
I'd be happy to discuss it with you and see if it's something we could turn into a solution.
Book a call