2024-01-01 21:11:32 +00:00
|
|
|
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
|
2021-09-18 18:29:29 +00:00
|
|
|
// This module is browser compatible.
|
2021-07-15 21:37:53 +00:00
|
|
|
|
|
|
|
/**
|
2022-11-25 11:40:23 +00:00
|
|
|
* Splits the given array into chunks of the given size and returns them.
|
2021-07-15 21:37:53 +00:00
|
|
|
*
|
2024-05-20 07:34:47 +00:00
|
|
|
* @typeParam T Type of the elements in the input array.
|
2024-05-06 07:51:20 +00:00
|
|
|
*
|
|
|
|
* @param array The array to split into chunks.
|
2024-05-19 14:02:09 +00:00
|
|
|
* @param size The size of the chunks. This must be a positive integer.
|
2024-05-06 07:51:20 +00:00
|
|
|
*
|
|
|
|
* @returns An array of chunks of the given size.
|
|
|
|
*
|
|
|
|
* @example Basic usage
|
2021-07-30 14:49:46 +00:00
|
|
|
* ```ts
|
2024-04-29 02:57:30 +00:00
|
|
|
* import { chunk } from "@std/collections/chunk";
|
refactor(assert,async,bytes,cli,collections,crypto,csv,data-structures,datetime,dotenv,encoding,expect,fmt,front-matter,fs,html,http,ini,internal,io,json,jsonc,log,media-types,msgpack,net,path,semver,streams,testing,text,toml,ulid,url,uuid,webgpu,yaml): import from `@std/assert` (#5199)
* refactor: import from `@std/assert`
* update
2024-06-30 08:30:10 +00:00
|
|
|
* import { assertEquals } from "@std/assert";
|
2021-07-30 14:49:46 +00:00
|
|
|
*
|
2022-11-25 11:40:23 +00:00
|
|
|
* const words = [
|
|
|
|
* "lorem",
|
|
|
|
* "ipsum",
|
|
|
|
* "dolor",
|
|
|
|
* "sit",
|
|
|
|
* "amet",
|
|
|
|
* "consetetur",
|
|
|
|
* "sadipscing",
|
|
|
|
* ];
|
|
|
|
* const chunks = chunk(words, 3);
|
2021-07-15 21:37:53 +00:00
|
|
|
*
|
2022-11-25 11:40:23 +00:00
|
|
|
* assertEquals(
|
|
|
|
* chunks,
|
|
|
|
* [
|
|
|
|
* ["lorem", "ipsum", "dolor"],
|
|
|
|
* ["sit", "amet", "consetetur"],
|
|
|
|
* ["sadipscing"],
|
|
|
|
* ],
|
|
|
|
* );
|
2021-07-15 21:37:53 +00:00
|
|
|
* ```
|
|
|
|
*/
|
2021-09-01 08:05:50 +00:00
|
|
|
export function chunk<T>(array: readonly T[], size: number): T[][] {
|
2021-07-15 21:37:53 +00:00
|
|
|
if (size <= 0 || !Number.isInteger(size)) {
|
2024-05-07 05:54:29 +00:00
|
|
|
throw new RangeError(
|
2021-09-07 07:40:05 +00:00
|
|
|
`Expected size to be an integer greater than 0 but found ${size}`,
|
2021-07-15 21:37:53 +00:00
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2024-05-07 07:11:55 +00:00
|
|
|
const result: T[][] = [];
|
|
|
|
let index = 0;
|
2021-07-15 21:37:53 +00:00
|
|
|
|
2024-05-07 07:11:55 +00:00
|
|
|
while (index < array.length) {
|
|
|
|
result.push(array.slice(index, index + size));
|
|
|
|
index += size;
|
2021-07-15 21:37:53 +00:00
|
|
|
}
|
|
|
|
|
2024-05-07 07:11:55 +00:00
|
|
|
return result;
|
2021-07-15 21:37:53 +00:00
|
|
|
}
|