nTimes
Calls a function n times and returns an array of the results.
1./**2.* Calls a function n times and returns an array of the results.3.**/4.5./**6.* Calls a function n times and returns an array of the results.7.**/8.9.const nTimes = <T,>(fn: (i: number) => T, n: number = 1): T[] => {10.if (n < 0) {11.throw new Error('n must be greater than 0');12.}13.let result: T[] = [];14.for (let i = 0; i < n; i++) {15.result.push(fn(i));16.}17.return result;18.};19.20.export default nTimes;
1. Installtion
npx @jrtilak/lazykit add nTimes
2. Parameters
-
fn
((i: number) => T
)
The function to be called. It receives the index of the current call as an argument. -
n
(optional) (number
)
The number of times to call the functionfn
. Defaults to1
. Must be greater than or equal to0
.
3. Returns
T[]
Returns an array of results obtained by callingfn
n
times. Each result corresponds to the return value offn
for each call.
4. Type Parameters
T
The return type of the functionfn
. This allows thenTimes
function to return an array of results of the same type as that returned byfn
.
5. Usage
The nTimes
function allows you to execute a function n
times and collect each result in an array. It's particularly useful for cases where you need to initialize values or generate items based on iteration indices.
1. Example
1.import nTimes from "@/utils/nTimes";2.3.// Function to be executed multiple times4.const generateRandomNumber = (i) => Number(i + Math.random().toFixed(2));5.6.// Call generateRandomNumber 5 times7.const results = nTimes(generateRandomNumber, 5);8.9.console.log(results);10.// Example output: [0.36, 1.73, 2.18, 3.45, 4.07]
In this example, generateRandomNumber
is executed 5 times with the index passed in each call. The nTimes
utility collects the return values in an array, allowing for flexible repetitive function execution with unique values each time.