sigkey
v2.0.0
Published
Sortable string keys for ordered collections
Readme
Sigkey
Sortable string keys for ordered collections. Supports fractional indexing for drag-and-drop reordering.
pnpm add sigkeyExample
import { useSigkey } from 'sigkey'
const quests = useSigkey([
{ id: 1, quest: 'Steal the shinies' },
{ id: 2, quest: 'Sabotage the bridge' },
{ id: 3, quest: 'Poison the well' },
])
quests.items
// [
// { id: 1, quest: 'Steal the shinies', _sigkey: '000001' },
// { id: 2, quest: 'Sabotage the bridge', _sigkey: '000002' },
// { id: 3, quest: 'Poison the well', _sigkey: '000003' },
// ]
// reprioritize: move "Poison the well" up
const [shinies, bridge, well] = quests.items
quests.move(well, shinies, bridge)
quests.items
// [
// { id: 1, quest: 'Steal the shinies', _sigkey: '000001' },
// { id: 3, quest: 'Poison the well', _sigkey: '000001i' },
// { id: 2, quest: 'Sabotage the bridge', _sigkey: '000002' },
// ]API
useSigkey<T extends object>(initialItems: T[])
Manages _sigkey automatically. Returns:
items— array ofWithSigkey<T>, always in sorted ordersorted()— shallow copy ofitemspush(...items)— append after the last keyunshift(...items)— prepend before the first keyinsert(item, after, before)— insert between two reference itemsmove(item, after, before)— reposition an existing itemremove(item)— remove from the list
quests.push({ id: 4, quest: 'Blame the elves' })
quests.unshift({ id: 5, quest: 'Raid the pantry' })
const [a, b] = quests.items
quests.insert({ id: 6, quest: 'Set a trap' }, a, b)between(a: string | null, b: string | null): string
Generate a key that sorts between a and b. Pass null for open-ended bounds:
between(a, null)— afterabetween(null, b)— beforebbetween(null, null)— returns"000001"
generateNBetween(a: string | null, b: string | null, n: number): string[]
Generate n evenly-spaced keys between a and b, returned in sorted order.
after(key: string): string
Shorthand for between(key, null).
before(key: string): string
Shorthand for between(null, key).
compare(a: string, b: string): number
String comparator for sorting: items.sort((a, b) => compare(a._sigkey, b._sigkey)).
