diff --git a/src/utils/__tests__/group.spec-d.ts b/src/utils/__tests__/group.spec-d.ts index d58e9c5b..3c1bd545 100644 --- a/src/utils/__tests__/group.spec-d.ts +++ b/src/utils/__tests__/group.spec-d.ts @@ -7,11 +7,11 @@ import type Vehicle from '#fixtures/types/vehicle' import type testSubject from '../group' describe('unit-d:utils/group', () => { - it('should return { [H in K]?: T[number][] }', () => { + it('should return { [H in K]: T[number][] }', () => { // Arrange type T = Vehicle[] type K = Vehicle['year'] - type Expect = { [H in K]?: T[number][] } + type Expect = { [H in K]: T[number][] } // Expect expectTypeOf>().returns.toEqualTypeOf() diff --git a/src/utils/__tests__/group.spec.ts b/src/utils/__tests__/group.spec.ts index 70bdaf6e..318432f9 100644 --- a/src/utils/__tests__/group.spec.ts +++ b/src/utils/__tests__/group.spec.ts @@ -14,8 +14,8 @@ describe('unit:utils/group', () => { ] // Act + Expect - cases.forEach(([array, identity, expected]) => { - expect(testSubject(array, identity)).to.eql(expected) + cases.forEach(([arr, key, expected]) => { + expect(testSubject(arr, key)).to.eql(expected) }) }) }) diff --git a/src/utils/group.ts b/src/utils/group.ts index 23403763..4d34e40c 100644 --- a/src/utils/group.ts +++ b/src/utils/group.ts @@ -4,14 +4,16 @@ */ import type { Mapper, PropertyKey } from '#src/types' +import cast from './cast' +import isUndefined from './is-undefined' /** - * Groups each item in an array. + * Group each item in an array. * * The return value is a plain object with a key for each group, where each key * value is an array containing group items. * - * A `mapper` function is used to convert array items to group keys. + * A `key` function is used to map array items to group keys. * * @see {@linkcode Mapper} * @@ -21,32 +23,32 @@ import type { Mapper, PropertyKey } from '#src/types' * @template K - Identity key type * * @param {T} arr - Array to group - * @param {Mapper} mapper - Array item interpolator - * @return {Partial>} Groups object + * @param {Mapper} key - Group key mapper + * @return {Record} Groups object */ const group = < T extends readonly unknown[], K extends PropertyKey = PropertyKey >( arr: T, - mapper: Mapper -): { [H in K]?: T[number][] } => { - return arr.reduce<{ [H in K]?: T[number][] }>((acc, item, i) => { + key: Mapper +): { [H in K]: T[number][] } => { + return arr.reduce<{ [H in K]: T[number][] }>((acc, item, i) => { /** * Group key. * - * @const {K} key + * @const {K} k */ - const key: K = mapper(item, i, arr) + const k: K = key(item, i, arr) // initialize group - !acc[key] && (acc[key] = []) + isUndefined(acc[k]) && (acc[k] = []) // add group item - acc[key]!.push(item) + acc[k].push(item) return acc - }, {}) + }, cast({})) } export default group