// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
// This module is browser compatible.

/**
 * Splits the given array into chunks of the given size and returns them.
 *
 * @template T Type of the elements in the input array.
 *
 * @param array The array to split into chunks.
 * @param size The size of the chunks. This my be a positive integer.
 *
 * @returns An array of chunks of the given size.
 *
 * @example Basic usage
 * ```ts
 * import { chunk } from "@std/collections/chunk";
 * import { assertEquals } from "@std/assert/assert-equals";
 *
 * const words = [
 *   "lorem",
 *   "ipsum",
 *   "dolor",
 *   "sit",
 *   "amet",
 *   "consetetur",
 *   "sadipscing",
 * ];
 * const chunks = chunk(words, 3);
 *
 * assertEquals(
 *   chunks,
 *   [
 *     ["lorem", "ipsum", "dolor"],
 *     ["sit", "amet", "consetetur"],
 *     ["sadipscing"],
 *   ],
 * );
 * ```
 */
export function chunk<T>(array: readonly T[], size: number): T[][] {
  if (size <= 0 || !Number.isInteger(size)) {
    throw new RangeError(
      `Expected size to be an integer greater than 0 but found ${size}`,
    );
  }

  const result: T[][] = [];
  let index = 0;

  while (index < array.length) {
    result.push(array.slice(index, index + size));
    index += size;
  }

  return result;
}

// denoCacheMetadata={"headers":{"cache-control":"public, max-age=31536000, immutable","cf-ray":"a223e6564ee07db6-LAX","alt-svc":"h3=\":443\"; ma=86400","etag":"\"cd95ef2884afd29a2d3669a28cd0da0b\"","access-control-expose-headers":"*","content-length":"1302","content-security-policy":"default-src 'none'; script-src 'none'; style-src 'none'; img-src 'none'; font-src 'none'; connect-src 'none'; frame-src 'none'; object-src 'none'; frame-ancestors 'none'; sandbox; form-action 'none';","x-jsr-backend":"modules","report-to":"{\"group\":\"cf-nel\",\"max_age\":604800,\"endpoints\":[{\"url\":\"https://a.nel.cloudflare.com/report/v4?s=TmGb2SohXo%2F8XYwd3yN6HKskFFib%2F%2Ba4f8gyAp2PhLbZQAXnptdo1L0WdgWUobwppzDXMP8oHBUFdTFyCQ5X8NTVJFt9pgaSvWBCnErS3O73FQTL5faYUjE%3D\"}]}","access-control-allow-origin":"*","server":"cloudflare","set-cookie":"__cf_bm=3Jt6WcXOnDaN2d5lRCkinouNdZ5kkX5Z_VbccBYkfO4-1785241874.949402-1.0.1.1-dBfNglyopfmfPKUlMvkEhVW_63dNIMB.EcsXX8qPdZ2OKXS4S8wih2D0XNdDSwmmQzTW6W3fudF_aMDfq4aqoN5pYd2bMxsMb8xP7MnNqB.XWKj1TjhgDi5W6TlDq_fS; HttpOnly; SameSite=None; Secure; Path=/; Domain=jsr.io; Expires=Tue, 28 Jul 2026 13:01:15 GMT","date":"Tue, 28 Jul 2026 12:31:15 GMT","x-content-type-options":"nosniff","content-type":"text/typescript","cross-origin-resource-policy":"cross-origin","nel":"{\"report_to\":\"cf-nel\",\"success_fraction\":0.0,\"max_age\":604800}","x-robots-tag":"noindex","vary":"Origin"},"url":"https://jsr.io/@std/collections/0.224.2/chunk.ts","time":1785241875}