times
Invokes fn count times and returns an array of the results. The function receives the current index (0-based) on each call.
Try it
Section titled “Try it”Import
Section titled “Import”import { times } from "1o1-utils";import { times } from "1o1-utils/times";Signature
Section titled “Signature”function times<T>(params: { count: number; fn: (index: number) => T }): T[]Parameters
Section titled “Parameters”| Name | Type | Required | Description |
|---|---|---|---|
| count | number | Yes | The number of times to invoke fn (non-negative integer) |
| fn | (index: number) => T | Yes | The function to invoke; receives the current index |
Returns
Section titled “Returns”T[] — An array of length count containing the results of each invocation.
Examples
Section titled “Examples”times({ count: 3, fn: (i) => i * 2 });// => [0, 2, 4]// Generate a list of objectstimes({ count: 3, fn: (i) => ({ id: i, name: `item-${i}` }) });// => [{ id: 0, name: "item-0" }, { id: 1, name: "item-1" }, { id: 2, name: "item-2" }]// Random valuestimes({ count: 5, fn: () => Math.random() });// => [0.42, 0.91, 0.13, 0.77, 0.05]// Zero count returns an empty arraytimes({ count: 0, fn: (i) => i });// => []Edge Cases
Section titled “Edge Cases”- Throws if
countis not a number or isNaN. - Throws if
countis not an integer (includingInfinity). - Throws if
countis negative. - Throws if
fnis not a function. count: 0returns[]and does not invokefn.
Also known as
Section titled “Also known as”repeat, range, fill, generate
Prompt suggestion
Section titled “Prompt suggestion”I'm using 1o1-utils (npm: https://www.npmjs.com/package/1o1-utils, GitHub: https://github.com/pedrotroccoli/1o1-utils, LLM context: https://pedrotroccoli.github.io/1o1-utils/llms.txt). Show me how to use times to generate an array of N items by invoking a factory function.