/** * Split an array per `size` items. * * @param {T[]} input * @param {number} size * @return {T[][]} An array of arrays of the specified type. * @template T */ export const chunk = (input: T[], size: number): T[][] => { return input.reduce((array, item, index) => { return index % size === 0 ? [...array, [item]] : [...array.slice(0, -1), [...array.slice(-1)[0], item]]; }, []); }; /** * Batch the function calls to `handler` per `size` items. * * @param {(addresses: string[] | number[]) => Promise} handler A function that takes a batch of addresses and returns the balance for the addresses. * @param {number} size The size of the batches. * @param {string[] | number[]} addresses The addresses to batch. * @return {Promise} A promise with the balances. */ export const batch = async ( handler: (addresses: string[] | number[]) => Promise, size: number, addresses: string[] | number[] ): Promise => { const chunks = chunk(addresses as any, size); return chunks.reduce>(async (current, next) => { return Promise.resolve([...(await current), ...(await handler(next as string[]))]); }, Promise.resolve([])); };