Generic indexing helpers

Benchmark publishedon

Description

Compare generic helper styles for grouping typed records by a stable key.

Setup

type Product = {
  sku: string
  category: 'book' | 'tool' | 'game' | 'course'
  price: number
  stock: number
}

const products: Product[] = Array.from({ length: 1_500 }, (_, index) => ({
  sku: 'sku-' + index,
  category: (['book', 'tool', 'game', 'course'] as const)[index % 4],
  price: 10 + (index % 97),
  stock: index % 13,
}))

function bucketScore(item: Product): number {
  return item.price * (item.stock + 1)
}

Test Runner

Initializing...

Testing in
Test CaseOps/sec
Object buckets
const totals: Record<Product['category'], number> = {
  book: 0,
  tool: 0,
  game: 0,
  course: 0,
}

for (const product of products) {
  totals[product.category] += bucketScore(product)
}

return totals.book + totals.tool + totals.game + totals.course
ready
Map buckets
const totals = new Map<Product['category'], number>()

for (const product of products) {
  totals.set(product.category, (totals.get(product.category) || 0) + bucketScore(product))
}

return (totals.get('book') || 0) + (totals.get('tool') || 0) + (totals.get('game') || 0) + (totals.get('course') || 0)
ready
Generic group helper
function sumBy<T, K extends string>(items: T[], keyOf: (item: T) => K, valueOf: (item: T) => number): Record<K, number> {
  const out = {} as Record<K, number>
  for (const item of items) {
    const key = keyOf(item)
    out[key] = (out[key] || 0) + valueOf(item)
  }
  return out
}

const totals = sumBy(products, product => product.category, bucketScore)
return totals.book + totals.tool + totals.game + totals.course
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.

Revision 1
publishedon