Executes a function a specified number of times and collects the results into an array.

A synchronous repetition function that executes the given function for each index (from 0 to count-1) and collects the results into an array.

  // Generate an array of squares from 1 to 5
const squares = ArrayUtil.repeat(5)(index => (index + 1) ** 2);
console.log(squares); // [1, 4, 9, 16, 25]

// Generate an array of default user objects
const users = ArrayUtil.repeat(3)(index => ({
id: index + 1,
name: `User${index + 1}`,
email: `user${index + 1}@example.com`
}));
console.log(users);
// [
// { id: 1, name: 'User1', email: 'user1@example.com' },
// { id: 2, name: 'User2', email: 'user2@example.com' },
// { id: 3, name: 'User3', email: 'user3@example.com' }
// ]
  • Parameters

    • count: number

      The number of times to repeat (non-negative integer)

    Returns <T>(closure: (index: number) => T) => T[]

    A function that takes a closure and returns an array of results