Skip to content

Commit

Permalink
fix(esl-utils): simplified flat array utility
Browse files Browse the repository at this point in the history
Deprecation: use `Array.prototype.flat` instead of `flat` utility
  • Loading branch information
ala-n committed Apr 28, 2023
1 parent 45f282f commit 788a782
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 4 deletions.
8 changes: 5 additions & 3 deletions src/modules/esl-utils/misc/array.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,11 @@ export const tuple = <T>(arr: T[]): Tuple<T>[] => arr.reduce((acc: Tuple<T>[], e
return acc;
}, []);

/** Flat array - unwraps one level of nested arrays */
export const flat = <T>(arr: (null | T | T[])[]): T[] =>
arr.reduce((acc: T[], el) => el ? acc.concat(el) : acc, []) as T[];
/**
* Flat array - unwraps one level of nested arrays
* @deprecated use `Array.prototype.flat` instead
*/
export const flat = <T>(arr: (null | T | T[])[]): T[] => arr.flat(1) as T[];

/** Wraps passed object or primitive to array */
export const wrap = <T>(arr: undefined | null | T | T[]): T[] => {
Expand Down
4 changes: 3 additions & 1 deletion src/modules/esl-utils/misc/test/array.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,13 @@ describe('misc/array helper tests', () => {

test('flat', () => {
expect(flat([])).toEqual([]);
expect(flat([0])).toEqual([0]);
expect(flat([1])).toEqual([1]);
expect(flat([1, 2])).toEqual([1, 2]);
expect(flat([1, [2, 3]])).toEqual([1, 2, 3]);
expect(flat([[1, 2], [3, 4]])).toEqual([1, 2, 3, 4]);
expect(flat([[1], [2, 3, 4], [], [5]])).toEqual([1, 2, 3, 4, 5]);
expect(flat([null, 1, 2, 3, [4, 5], null, [6]])).toEqual([1, 2, 3, 4, 5, 6]);
expect(flat([null, 1, 2, 3, [4, 5], null, [6]])).toEqual([null, 1, 2, 3, 4, 5, null, 6]);
});

test('wrap', () => {
Expand All @@ -43,6 +44,7 @@ describe('misc/array helper tests', () => {

test('range', () => {
expect(range(3)).toEqual([0, 1, 2]);
// @ts-ignore
expect(range(9, (x) => x / 8)).toEqual([...Array(9).keys()].map((x) => x / 8));
});

Expand Down

0 comments on commit 788a782

Please sign in to comment.