npm.io
2.0.0 • Published 8 months ago

sigkey

Licence
MIT
Version
2.0.0
Deps
0
Size
10 kB
Vulns
0
Weekly
0
Stars
1

Sigkey

Sortable string keys for ordered collections. Supports fractional indexing for drag-and-drop reordering.

pnpm add sigkey

Example

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 of WithSigkey<T>, always in sorted order
  • sorted() — shallow copy of items
  • push(...items) — append after the last key
  • unshift(...items) — prepend before the first key
  • insert(item, after, before) — insert between two reference items
  • move(item, after, before) — reposition an existing item
  • remove(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) — after a
  • between(null, b) — before b
  • between(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)).