repeatArray
Returns a new array with the input array repeated a specified number of times.
1/**
2 * Returns a new array with the input array repeated a specified number of times.
3 *
4 * @param arr - The array to repeat.
5 * @param times - The number of times to repeat the array. Must be a non-negative integer.
6 * @returns A new array with repeated content.
7 */
8export function repeatArray<T>(arr: T[], times: number): T[] {
9 if (!Number.isInteger(times) || times < 0) {
10 throw new Error('"times" must be a non-negative integer');
11 }
12 return Array.from({ length: times }, () => arr).flat();
13}
Concise and expressive
Utilizes
Array.from
withflat()
for compact, readable logic that avoids verbose loop code.Immutability
Returns a new array without modifying the original, adhering to functional programming principles.
Robust parameter validation
Throws an explicit error if
times
is not a non-negative integer, helping avoid silent runtime bugs.Generic type-safe implementation
Fully generic using
T[]
, preserving type correctness across repeated segments.Efficient for small to medium repetitions
Performance is suitable for UI and general logic use cases where repetitions are not excessive.
Tests | Examples
1test('repeatArray - repeat 3 times', () => {
2 expect(repeatArray([1, 2], 3)).toEqual([1, 2, 1, 2, 1, 2]);
3});
4
5test('repeatArray - repeat 1 time', () => {
6 expect(repeatArray(['a'], 1)).toEqual(['a']);
7});
8
9test('repeatArray - repeat 0 times', () => {
10 expect(repeatArray([42], 0)).toEqual([]);
11});
12
13test('repeatArray - empty array', () => {
14 expect(repeatArray([], 5)).toEqual([]);
15});
16
17test('repeatArray - throws on negative times', () => {
18 expect(() => repeatArray([1, 2], -1)).toThrow();
19});
20
21test('repeatArray - throws on non-integer times', () => {
22 expect(() => repeatArray([1, 2], 2.5)).toThrow();
23});
Common Use Cases
Mock data generation
Repeating sample structures to fill space or test pagination, infinite scroll, or list rendering behavior.
CSS grid and layout scenarios
Useful for replicating component instances when templating UI elements in predictable patterns.
Test data or load simulation
Creating longer sequences of predefined values for testing performance or user interaction behavior.
Repeating audio/video frames or instructions
Helpful in media and game development where sequences need to loop a fixed number of times.
Form input presets
Prefilling form fields with repeated options or default sets based on user-defined length.