Skip to content

Commit

Permalink
[patch] add Partial to return type of groupArrayBy and arrayToObject
Browse files Browse the repository at this point in the history
  • Loading branch information
electrovir committed May 16, 2024
1 parent 123c532 commit 421737a
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 9 deletions.
4 changes: 2 additions & 2 deletions packages/common-tests/src/tests/array/array.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -412,7 +412,7 @@ describe(groupArrayBy.name, () => {
return TestEnum.Second;
}
}),
).toEqualTypeOf<Record<TestEnum, {a: number; b: string}[]>>();
).toEqualTypeOf<Partial<Record<TestEnum, {a: number; b: string}[]>>>();
});
});

Expand Down Expand Up @@ -549,7 +549,7 @@ describe(arrayToObject.name, () => {
return TestEnum.Second;
}
}),
).toEqualTypeOf<Record<TestEnum, {a: number; b: string}>>();
).toEqualTypeOf<Partial<Record<TestEnum, {a: number; b: string}>>>();
});
});

Expand Down
13 changes: 6 additions & 7 deletions packages/common/src/augments/array/array.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import {getOrSet} from '../object/get-or-set';
import {typedObjectFromEntries} from '../object/object-entries';
import {AtLeastTuple} from '../tuple';
import {ArrayElement} from '../type';
Expand Down Expand Up @@ -69,20 +70,18 @@ export function groupArrayBy<ElementType, NewKey extends PropertyKey>(
index: number,
originalArray: ReadonlyArray<ElementType>,
) => NewKey,
): Record<NewKey, ElementType[]> {
): Partial<Record<NewKey, ElementType[]>> {
return inputArray.reduce(
(accum, entry, index, originalArray) => {
const key = callback(entry, index, originalArray);
if (!(key in accum)) {
accum[key] = [];
}
const entryArray: ElementType[] = getOrSet(accum, key, () => [] as ElementType[]);

accum[key].push(entry);
entryArray.push(entry);

return accum;
},
{} as Record<NewKey, ElementType[]>,
);
) as Partial<Record<NewKey, ElementType[]>>;
}

/**
Expand All @@ -96,7 +95,7 @@ export function arrayToObject<ElementType, NewKey extends PropertyKey>(
index: number,
originalArray: ReadonlyArray<ElementType>,
) => NewKey,
): Record<NewKey, ElementType> {
): Partial<Record<NewKey, ElementType>> {
return typedObjectFromEntries(
inputArray.map((entry, index, originalArray) => {
const key = callback(entry, index, originalArray);
Expand Down

0 comments on commit 421737a

Please sign in to comment.