groupBy

Benchmark created on


Setup

function groupBy(
  items,
  createKey,
  createValue
) {
  return items.reduce((result, item) => {
    const key = createKey(item)
    // If there is no createValue function, Item and Value are the same.
    // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
    const value = createValue?.item || item

    if (result.has(key)) {
      result.get(key)?.push(value)
    } else {
      result.set(key, [value])
    }

    return result
  }, new Map())
}

const data = Array.from({length: 1000}, (_, idx) => ({id: idx % 250, otherValue: Math.random(), otherValue2: Math.random()}))

Test runner

Ready to run.

Testing in
TestOps/sec
custom groupBy Function
const map = groupBy(data, (obj) => obj.id)
ready
native Map.groupBy
const map = Map.groupBy(data, (obj) => obj.id)
ready

Revisions

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