Skip to content

Commit

Permalink
chore: Remove lodash times in favor of foundation fn
Browse files Browse the repository at this point in the history
  • Loading branch information
spalladino committed Jan 18, 2024
1 parent 52162ee commit 19c7dad
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 0 deletions.
13 changes: 13 additions & 0 deletions yarn-project/foundation/src/collection/array.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { times } from './array.js';

describe('times', () => {
it('should return an array with the result from all executions', () => {
const result = times(5, i => i * 2);
expect(result).toEqual([0, 2, 4, 6, 8]);
});

it('should return an empty array when n is 0', () => {
const result = times(0, i => i * 2);
expect(result).toEqual([]);
});
});
10 changes: 10 additions & 0 deletions yarn-project/foundation/src/collection/array.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,3 +52,13 @@ export function isArrayEmpty<T>(arr: T[], isEmpty: (item: T) => boolean): boolea
export function arrayNonEmptyLength<T>(arr: T[], isEmpty: (item: T) => boolean): number {
return arr.reduce((sum, item) => (isEmpty(item) ? sum : sum + 1), 0);
}

/**
* Executes the given function n times and returns the results in an array.
* @param n - How many times to repeat.
* @param fn - Mapper from index to value.
* @returns The array with the result from all executions.
*/
export function times<T>(n: number, fn: (i: number) => T): T[] {
return [...Array(n).keys()].map(i => fn(i));
}

0 comments on commit 19c7dad

Please sign in to comment.