Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(collections/unstable): Iterable argument in chunk() #5925

Merged
merged 3 commits into from
Sep 23, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions collections/deno.json
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
"./take-while": "./take_while.ts",
"./union": "./union.ts",
"./unstable-take-while": "./unstable_take_while.ts",
"./unstable-chunk": "./unstable_chunk.ts",
"./unzip": "./unzip.ts",
"./without-all": "./without_all.ts",
"./zip": "./zip.ts"
Expand Down
75 changes: 75 additions & 0 deletions collections/unstable_chunk.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
// This module is browser compatible.

/**
* Splits the given array into an array of chunks of the given size and returns them.
*
* @experimental **UNSTABLE**: New API, yet to be vetted.
*
* @typeParam T The type of the elements in the iterable.
*
* @param iterable The iterable to take elements from.
* @param predicate The size of the chunks. This must be a positive integer.
*
* @returns An array of chunks of the given size.
*
* @example Basic usage
* ```ts
* import { chunk } from "@std/collections/unstable-chunk";
* import { assertEquals } from "@std/assert";
*
* 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>(
iterable: Iterable<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[][] = [];

// Faster path
if (Array.isArray(iterable)) {
let index = 0;
while (index < iterable.length) {
result.push(iterable.slice(index, index + size));
index += size;
}
return result;
}

let chunk: T[] = [];
for (const item of iterable) {
chunk.push(item);
if (chunk.length === size) {
result.push(chunk);
chunk = [];
}
}
if (chunk.length > 0) {
result.push(chunk);
}
return result;
}
202 changes: 202 additions & 0 deletions collections/unstable_chunk_test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,202 @@
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.

import { assertEquals, assertThrows } from "@std/assert";
import { chunk } from "./unstable_chunk.ts";

Deno.test("(unstable) chunk() does not mutate the input", () => {
const array = [1, 2, 3, 4];
chunk(array, 2);
assertEquals(array, [1, 2, 3, 4], "Input array should not be mutated");
});

Deno.test("(unstable) chunk() throws on non naturals", () => {
assertThrows(
() => chunk([], +.5),
RangeError,
"Expected size to be an integer greater than 0 but found 0.5",
);
assertThrows(
() => chunk([], -4.7),
RangeError,
"Expected size to be an integer greater than 0 but found -4.7",
);
assertThrows(
() => chunk([], -2),
RangeError,
"Expected size to be an integer greater than 0 but found -2",
);
assertThrows(
() => chunk([], +0),
RangeError,
"Expected size to be an integer greater than 0 but found 0",
);
assertThrows(
() => chunk([], -0),
RangeError,
"Expected size to be an integer greater than 0 but found 0",
);
});

Deno.test("(unstable) chunk() returns empty array when input is empty", () => {
const actual = chunk([], 1);
assertEquals(actual, [], "Empty input should return empty array");
});

Deno.test({
name: "(unstable) chunk() handles single element chunks",
fn() {
assertEquals(chunk([1, 2, 3, 4, 5, 6], 1), [[1], [2], [3], [4], [5], [6]]);
assertEquals(chunk(["foo"], 1), [["foo"]]);
assertEquals(chunk([null], 1), [[null]]);
assertEquals(chunk([undefined], 1), [[undefined]]);
},
});

Deno.test("(unstable) chunk() handles n chunks fitting", () => {
assertEquals(
chunk([1, 2, 3, 4, 5, 6], 2),
[[1, 2], [3, 4], [5, 6]],
"size=2",
);
assertEquals(chunk([1, 2, 3, 4, 5, 6], 3), [[1, 2, 3], [4, 5, 6]], "size=3");
});

Deno.test("chunk() handles n chunks not fitting", () => {
assertEquals(
chunk([1, 2, 3, 4, 5, 6], 4),
[[1, 2, 3, 4], [5, 6]],
"size 4 with 6 elements should return 2 chunks with 4 and 2 elements",
);
assertEquals(
chunk([1, 2, 3, 4, 5, 6], 5),
[[1, 2, 3, 4, 5], [6]],
"size 5 with 6 elements should return 2 chunks with 5 and 1 elements",
);
});

Deno.test("(unstable) chunk() handles n chunks larger than input length", () => {
assertEquals(
chunk([1, 2, 3, 4, 5, 6], 10),
[[1, 2, 3, 4, 5, 6]],
);
});

Deno.test({
name: "(unstable) chunk() handles chunks equal to length",
fn() {
assertEquals(
chunk([1, 2, 3, 4, 5, 6], 6),
[[1, 2, 3, 4, 5, 6]],
);
},
});

Deno.test("(unstable) chunk() handles a generator", () => {
function* gen() {
yield "a";
yield "b";
yield "c";
yield "d";
}
assertEquals(chunk(gen(), 1), [["a"], ["b"], ["c"], ["d"]], "size = 1");
assertEquals(chunk(gen(), 2), [["a", "b"], ["c", "d"]], "size = 2");
assertEquals(chunk(gen(), 3), [["a", "b", "c"], ["d"]], "size = 3");
assertEquals(chunk(gen(), 4), [["a", "b", "c", "d"]], "size = gen.length");
assertEquals(chunk(gen(), 5), [["a", "b", "c", "d"]], "size > gen.length");
});

Deno.test("(unstable) chunk() handles a string", () => {
assertEquals(chunk("abcdefg", 4), [
["a", "b", "c", "d"],
["e", "f", "g"],
]);
});

Deno.test("(unstable) chunk() handles a Set", () => {
const set = new Set([1, 2, 3, 4, 5, 6]);
assertEquals(chunk(set, 2), [
[1, 2],
[3, 4],
[5, 6],
]);
});

Deno.test("(unstable) chunk() handles a Map", () => {
const map = new Map([
["a", 1],
["b", 2],
["c", 3],
["d", 4],
["e", 5],
["f", 6],
]);
assertEquals(chunk(map, 2), [
[
["a", 1],
["b", 2],
],
[
["c", 3],
["d", 4],
],
[
["e", 5],
["f", 6],
],
]);
});

Deno.test("(unstable) chunk() handles user-defined iterable", () => {
class MyIterable {
*[Symbol.iterator]() {
yield 1;
yield 2;
yield 3;
yield 4;
yield 5;
yield 6;
}
}
assertEquals(chunk(new MyIterable(), 2), [
[1, 2],
[3, 4],
[5, 6],
]);
});

Deno.test("(unstable) chunk() handles a TypedArrays", () => {
const typedArrays = [
Uint8Array,
Uint8ClampedArray,
Uint16Array,
Uint32Array,
Int8Array,
Int16Array,
Int32Array,
Float32Array,
Float64Array,
];
for (const TypedArray of typedArrays) {
const array = new TypedArray([1, 2, 3, 4, 5, 6]);
assertEquals(chunk(array, 2), [
[1, 2],
[3, 4],
[5, 6],
]);
}
});

Deno.test("(unstable) chunk() handles an array with empty slots", () => {
// Regression test for chunk that only allowed Array instances instead of any Iterable.
// This is a special case where an array is filled with empty slots which is a different kind of nothing than null or undefined
// Typed arrays are not affected, as they are filled with 0 instead of empty slots
const arr = new Array(4);
arr[2] = 3;

const expectedSecondChunk = new Array(2);
expectedSecondChunk[0] = 3;
assertEquals(chunk(arr, 2), [
new Array(2),
expectedSecondChunk,
]);
});