Skip to content

Truly independent web browser

LibJS: Implement Iterator.prototype.chunks

Timothy Flynn06cb7cc88e81
diff --git a/Libraries/LibJS/Rust/src/runtime/common_property_names.rs b/Libraries/LibJS/Rust/src/runtime/common_property_names.rs
index e641725860a..960fa4c76fc 100644
--- a/Libraries/LibJS/Rust/src/runtime/common_property_names.rs
+++ b/Libraries/LibJS/Rust/src/runtime/common_property_names.rs
@@ -125,6 +125,7 @@ define_common_property_names! {
ceil,
charAt,
charCodeAt,
+ chunks,
clear,
clz32,
codePointAt,
diff --git a/Libraries/LibJS/Rust/src/runtime/error_types.rs b/Libraries/LibJS/Rust/src/runtime/error_types.rs
index de6f6d418ba..abfbefde17a 100644
--- a/Libraries/LibJS/Rust/src/runtime/error_types.rs
+++ b/Libraries/LibJS/Rust/src/runtime/error_types.rs
@@ -146,6 +146,7 @@ define_error_types! {
NumberIsNaN => "{} must not be NaN",
NumberIsNaNOrInfinity => "Number must not be NaN or Infinity",
NumberIsNegative => "{} must not be negative",
+ NumberIsOutOfRange => "{} must be between {} and {} inclusive",
ObjectDefineOwnPropertyReturnedFalse => "Object's [[DefineOwnProperty]] method returned false",
ObjectDeleteReturnedFalse => "Object's [[Delete]] method returned false",
ObjectFreezeFailed => "Could not freeze object",
diff --git a/Libraries/LibJS/Rust/src/runtime/iterator_helper.rs b/Libraries/LibJS/Rust/src/runtime/iterator_helper.rs
index 891b1ca52e1..10f7e4c1d9e 100644
--- a/Libraries/LibJS/Rust/src/runtime/iterator_helper.rs
+++ b/Libraries/LibJS/Rust/src/runtime/iterator_helper.rs
@@ -31,6 +31,10 @@ pub const ITERATOR_HELPER_BRAND: &str = "Iterator Helper";
/// lives in cells they capture.
#[derive(Clone, Copy, Trace)]
pub enum IteratorHelperClosure {
+ Chunks {
+ iterated: Gc<IteratorRecord>,
+ chunk_size: u32,
+ },
Concat {
iterables: Gc<ConcatIterator>,
},
@@ -63,6 +67,7 @@ pub enum IteratorHelperClosure {
impl IteratorHelperClosure {
fn call(self, vm: &Vm, iterator: &IteratorHelper) -> ThrowCompletionOr<IterationResult> {
match self {
+ Self::Chunks { iterated, chunk_size } => iterator_prototype::chunks_closure(vm, iterated, chunk_size),
Self::Concat { iterables } => iterables.next(vm, iterator),
Self::Drop {
iterated,
@@ -88,6 +93,7 @@ impl IteratorHelperClosure {
/// The abrupt closure, for the helpers that have one.
fn abrupt_closure(self, vm: &Vm, completion: Completion) -> Option<ThrowCompletionOr<Value>> {
match self {
+ Self::Chunks { iterated, .. } if iterated.done() => Some(completion.into_throw_completion_or()),
Self::Concat { iterables } => Some(iterables.on_abrupt_completion(vm, completion)),
Self::FlatMap {
iterated,
@@ -95,7 +101,9 @@ impl IteratorHelperClosure {
..
} => Some(flat_map_iterator.on_abrupt_completion(vm, iterated, completion)),
Self::Zip { zip_iterator } => Some(zip_iterator.on_abrupt_completion(vm, completion)),
- Self::Drop { .. } | Self::Filter { .. } | Self::Map { .. } | Self::Take { .. } => None,
+ Self::Chunks { .. } | Self::Drop { .. } | Self::Filter { .. } | Self::Map { .. } | Self::Take { .. } => {
+ None
+ }
}
}
}
diff --git a/Libraries/LibJS/Rust/src/runtime/iterator_prototype.rs b/Libraries/LibJS/Rust/src/runtime/iterator_prototype.rs
index 33a5f0a70d2..9bb640afc6a 100644
--- a/Libraries/LibJS/Rust/src/runtime/iterator_prototype.rs
+++ b/Libraries/LibJS/Rust/src/runtime/iterator_prototype.rs
@@ -73,7 +73,7 @@ fn return_undefined() -> HelperIterationResult {
}
impl IteratorPrototype {
- // 27.1.2 The %IteratorPrototype% Object, https://tc39.es/ecma262/#sec-%iteratorprototype%-object
+ // 27.1.3.3 Properties of the Iterator Prototype Object, https://tc39.es/ecma262/#sec-%iteratorprototype%-object
pub fn create(vm: &Vm, realm: Gc<Realm>) -> Gc<IteratorPrototype> {
realm.create_object(vm, |_| IteratorPrototype {
base: Object::new_with_prototype(
@@ -96,6 +96,7 @@ impl IteratorPrototype {
raw_native!(IteratorPrototype::symbol_iterator),
0,
);
+ define(&names.chunks, raw_native!(IteratorPrototype::chunks), 1);
define(&names.drop, raw_native!(IteratorPrototype::drop), 1);
define(&names.every, raw_native!(IteratorPrototype::every), 1);
define(&names.filter, raw_native!(IteratorPrototype::filter), 1);
@@ -115,7 +116,7 @@ impl IteratorPrototype {
0,
);
- // 27.1.4.1 Iterator.prototype.constructor, https://tc39.es/ecma262/#sec-iterator.prototype.constructor
+ // 27.1.3.3.2 Iterator.prototype.constructor, https://tc39.es/ecma262/#sec-iterator.prototype.constructor
object.define_native_accessor(
vm,
realm,
@@ -125,7 +126,7 @@ impl IteratorPrototype {
PropertyAttributes::new(Attribute::CONFIGURABLE),
);
- // 27.1.4.14 Iterator.prototype [ %Symbol.toStringTag% ], https://tc39.es/ecma262/#sec-iterator.prototype-%symbol.tostringtag%
+ // 27.1.3.3.18 Iterator.prototype [ %Symbol.toStringTag% ], https://tc39.es/ecma262/#sec-iterator.prototype-%symbol.tostringtag%
object.define_native_accessor(
vm,
realm,
@@ -136,7 +137,63 @@ impl IteratorPrototype {
);
}
- // 27.1.4.1.1 get Iterator.prototype.constructor, https://tc39.es/ecma262/#sec-get-iterator.prototype.constructor
+ // 27.1.3.3.1 Iterator.prototype.chunks ( chunkSize ), https://tc39.es/ecma262/#sec-iterator.prototype.chunks
+ fn chunks(vm: &Vm) -> ThrowCompletionOr<Value> {
+ let realm = current_realm(vm);
+ let chunk_size = vm.argument(0);
+
+ // 1. Let obj be the this value.
+ // 2. If obj is not an Object, throw a TypeError exception.
+ let object = this_object(vm)?;
+
+ // 3. Let iterated be the Iterator Record { [[Iterator]]: obj, [[NextMethod]]: undefined, [[Done]]: false }.
+ let mut iterated = IteratorRecord::create(vm, Some(object), Value::UNDEFINED, false);
+
+ // 4. If chunkSize is not an integral Number, then
+ if !chunk_size.is_integral_number() {
+ // a. Let error be ThrowCompletion(a newly created TypeError object).
+ let error = vm.throw_completion::<Value>(
+ ErrorKind::TypeError,
+ ErrorType::IsNotAn,
+ &[&"chunkSize", &"integral Number"],
+ );
+
+ // b. Return ? IteratorClose(iterated, error).
+ return iterator_close(vm, &iterated, Completion::from(error)).into_throw_completion_or();
+ }
+
+ // 5. If chunkSize is not in the inclusive interval from 1𝔽 to 𝔽(2**32 - 1), then
+ if !(1.0..=f64::from(u32::MAX)).contains(&chunk_size.as_f64()) {
+ // a. Let error be ThrowCompletion(a newly created RangeError object).
+ let error = vm.throw_completion::<Value>(
+ ErrorKind::RangeError,
+ ErrorType::NumberIsOutOfRange,
+ &[&"chunkSize", &"1", &"2^32-1"],
+ );
+
+ // b. Return ? IteratorClose(iterated, error).
+ return iterator_close(vm, &iterated, Completion::from(error)).into_throw_completion_or();
+ }
+
+ // 6. Set iterated to ? GetIteratorDirect(obj).
+ iterated = get_iterator_direct(vm, object)?;
+
+ // 7. Let closure be a new Abstract Closure with no parameters that captures iterated and chunkSize and performs
+ // the following steps when called:
+ let closure = IteratorHelperClosure::Chunks {
+ iterated,
+ chunk_size: chunk_size.as_f64() as u32,
+ };
+
+ // 8. Let result be CreateIteratorFromClosure(closure, "Iterator Helper", %IteratorHelperPrototype%, « [[UnderlyingIterators]] »).
+ // 9. Set result.[[UnderlyingIterators]] to « iterated ».
+ let result = IteratorHelper::create(vm, realm, &underlying_iterators_of_one(vm, iterated), closure);
+
+ // 10. Return result.
+ Ok(Value::from_object(result))
+ }
+
+ // 27.1.3.3.2.1 get Iterator.prototype.constructor, https://tc39.es/ecma262/#sec-get-iterator.prototype.constructor
#[allow(clippy::unnecessary_wraps, reason = "native functions can throw")]
fn constructor_getter(vm: &Vm) -> ThrowCompletionOr<Value> {
let realm = current_realm(vm);
@@ -145,7 +202,7 @@ impl IteratorPrototype {
Ok(Value::from_object(realm.intrinsics().iterator_constructor(vm)))
}
- // 27.1.4.1.2 set Iterator.prototype.constructor, https://tc39.es/ecma262/#sec-set-iterator.prototype.constructor
+ // 27.1.3.3.2.2 set Iterator.prototype.constructor, https://tc39.es/ecma262/#sec-set-iterator.prototype.constructor
fn constructor_setter(vm: &Vm) -> ThrowCompletionOr<Value> {
let realm = current_realm(vm);
@@ -162,7 +219,7 @@ impl IteratorPrototype {
Ok(Value::UNDEFINED)
}
- // 27.1.4.2 Iterator.prototype.drop ( limit ), https://tc39.es/ecma262/#sec-iterator.prototype.drop
+ // 27.1.3.3.3 Iterator.prototype.drop ( limit ), https://tc39.es/ecma262/#sec-iterator.prototype.drop
fn drop(vm: &Vm) -> ThrowCompletionOr<Value> {
let realm = current_realm(vm);
@@ -231,7 +288,7 @@ impl IteratorPrototype {
Ok(Value::from_object(result))
}
- // 27.1.4.3 Iterator.prototype.every ( predicate ), https://tc39.es/ecma262/#sec-iterator.prototype.every
+ // 27.1.3.3.4 Iterator.prototype.every ( predicate ), https://tc39.es/ecma262/#sec-iterator.prototype.every
fn every(vm: &Vm) -> ThrowCompletionOr<Value> {
let predicate = vm.argument(0);
@@ -290,7 +347,7 @@ impl IteratorPrototype {
}
}
- // 27.1.4.4 Iterator.prototype.filter ( predicate ), https://tc39.es/ecma262/#sec-iterator.prototype.filter
+ // 27.1.3.3.5 Iterator.prototype.filter ( predicate ), https://tc39.es/ecma262/#sec-iterator.prototype.filter
fn filter(vm: &Vm) -> ThrowCompletionOr<Value> {
let realm = current_realm(vm);
@@ -330,7 +387,7 @@ impl IteratorPrototype {
Ok(Value::from_object(result))
}
- // 27.1.4.5 Iterator.prototype.find ( predicate ), https://tc39.es/ecma262/#sec-iterator.prototype.find
+ // 27.1.3.3.6 Iterator.prototype.find ( predicate ), https://tc39.es/ecma262/#sec-iterator.prototype.find
fn find(vm: &Vm) -> ThrowCompletionOr<Value> {
let predicate = vm.argument(0);
@@ -389,7 +446,7 @@ impl IteratorPrototype {
}
}
- // 27.1.4.6 Iterator.prototype.flatMap ( mapper ), https://tc39.es/ecma262/#sec-iterator.prototype.flatmap
+ // 27.1.3.3.7 Iterator.prototype.flatMap ( mapper ), https://tc39.es/ecma262/#sec-iterator.prototype.flatmap
fn flat_map(vm: &Vm) -> ThrowCompletionOr<Value> {
let realm = current_realm(vm);
@@ -432,7 +489,7 @@ impl IteratorPrototype {
Ok(Value::from_object(result))
}
- // 27.1.4.7 Iterator.prototype.forEach ( procedure ), https://tc39.es/ecma262/#sec-iterator.prototype.foreach
+ // 27.1.3.3.8 Iterator.prototype.forEach ( procedure ), https://tc39.es/ecma262/#sec-iterator.prototype.foreach
fn for_each(vm: &Vm) -> ThrowCompletionOr<Value> {
let procedure = vm.argument(0);
@@ -579,7 +636,7 @@ impl IteratorPrototype {
}
}
- // 27.1.3.3.8 Iterator.prototype.join ( separator ), https://tc39.es/ecma262/#sec-iterator.prototype.join
+ // 27.1.3.3.9 Iterator.prototype.join ( separator ), https://tc39.es/ecma262/#sec-iterator.prototype.join
fn join(vm: &Vm) -> ThrowCompletionOr<Value> {
let separator = vm.argument(0);
@@ -647,7 +704,7 @@ impl IteratorPrototype {
}
}
- // 27.1.4.9 Iterator.prototype.map ( mapper ), https://tc39.es/ecma262/#sec-iterator.prototype.map
+ // 27.1.3.3.10 Iterator.prototype.map ( mapper ), https://tc39.es/ecma262/#sec-iterator.prototype.map
fn map(vm: &Vm) -> ThrowCompletionOr<Value> {
let realm = current_realm(vm);
@@ -687,7 +744,7 @@ impl IteratorPrototype {
Ok(Value::from_object(result))
}
- // 27.1.4.10 Iterator.prototype.reduce ( reducer [ , initialValue ] ), https://tc39.es/ecma262/#sec-iterator.prototype.reduce
+ // 27.1.3.3.11 Iterator.prototype.reduce ( reducer [ , initialValue ] ), https://tc39.es/ecma262/#sec-iterator.prototype.reduce
fn reduce(vm: &Vm) -> ThrowCompletionOr<Value> {
let reducer = vm.argument(0);
@@ -768,7 +825,7 @@ impl IteratorPrototype {
}
}
- // 27.1.4.11 Iterator.prototype.some ( predicate ), https://tc39.es/ecma262/#sec-iterator.prototype.some
+ // 27.1.3.3.12 Iterator.prototype.some ( predicate ), https://tc39.es/ecma262/#sec-iterator.prototype.some
fn some(vm: &Vm) -> ThrowCompletionOr<Value> {
let predicate = vm.argument(0);
@@ -827,7 +884,7 @@ impl IteratorPrototype {
}
}
- // 27.1.4.12 Iterator.prototype.take ( limit ), https://tc39.es/ecma262/#sec-iterator.prototype.take
+ // 27.1.3.3.13 Iterator.prototype.take ( limit ), https://tc39.es/ecma262/#sec-iterator.prototype.take
fn take(vm: &Vm) -> ThrowCompletionOr<Value> {
let realm = current_realm(vm);
@@ -896,7 +953,7 @@ impl IteratorPrototype {
Ok(Value::from_object(result))
}
- // 27.1.4.13 Iterator.prototype.toArray ( ), https://tc39.es/ecma262/#sec-iterator.prototype.toarray
+ // 27.1.3.3.14 Iterator.prototype.toArray ( ), https://tc39.es/ecma262/#sec-iterator.prototype.toarray
fn to_array(vm: &Vm) -> ThrowCompletionOr<Value> {
let realm = current_realm(vm);
@@ -925,7 +982,7 @@ impl IteratorPrototype {
}
}
- // 27.1.4.14 Iterator.prototype [ %Symbol.dispose% ] ( ), https://tc39.es/ecma262/#sec-iterator.prototype-%symbol.dispose%
+ // 27.1.3.3.16 Iterator.prototype [ %Symbol.dispose% ] ( ), https://tc39.es/ecma262/#sec-iterator.prototype-%symbol.dispose%
fn symbol_dispose(vm: &Vm) -> ThrowCompletionOr<Value> {
// 1. Let obj be the this value.
let object = vm.this_value();
@@ -943,14 +1000,14 @@ impl IteratorPrototype {
Ok(Value::UNDEFINED)
}
- // 27.1.4.15 Iterator.prototype [ %Symbol.iterator% ] ( ), https://tc39.es/ecma262/#sec-iterator.prototype-%symbol.iterator%
+ // 27.1.3.3.17 Iterator.prototype [ %Symbol.iterator% ] ( ), https://tc39.es/ecma262/#sec-iterator.prototype-%symbol.iterator%
#[allow(clippy::unnecessary_wraps, reason = "native functions can throw")]
fn symbol_iterator(vm: &Vm) -> ThrowCompletionOr<Value> {
// 1. Return the this value.
Ok(vm.this_value())
}
- // 27.1.4.16.1 get Iterator.prototype [ %Symbol.toStringTag% ], https://tc39.es/ecma262/#sec-get-iterator.prototype-%symbol.tostringtag%
+ // 27.1.3.3.18.1 get Iterator.prototype [ %Symbol.toStringTag% ], https://tc39.es/ecma262/#sec-get-iterator.prototype-%symbol.tostringtag%
#[allow(clippy::unnecessary_wraps, reason = "native functions can throw")]
fn to_string_tag_getter(vm: &Vm) -> ThrowCompletionOr<Value> {
// 1. Return "Iterator".
@@ -960,7 +1017,7 @@ impl IteratorPrototype {
)))
}
- // 27.1.4.16.2 set Iterator.prototype [ %Symbol.toStringTag% ], https://tc39.es/ecma262/#sec-set-iterator.prototype-%symbol.tostringtag%
+ // 27.1.3.3.18.2 set Iterator.prototype [ %Symbol.toStringTag% ], https://tc39.es/ecma262/#sec-set-iterator.prototype-%symbol.tostringtag%
fn to_string_tag_setter(vm: &Vm) -> ThrowCompletionOr<Value> {
let realm = current_realm(vm);
@@ -978,6 +1035,59 @@ impl IteratorPrototype {
}
}
+/// The closure of Iterator.prototype.chunks, step 7.
+pub fn chunks_closure(
+ vm: &Vm,
+ iterated: Gc<IteratorRecord>,
+ chunk_size: u32,
+) -> ThrowCompletionOr<HelperIterationResult> {
+ // NB: Resuming after the final partial chunk returns without advancing the underlying iterator.
+ if iterated.done() {
+ return Ok(return_undefined());
+ }
+
+ // a. Let buffer be a new empty List.
+ let buffer = MarkedVec::new(vm);
+
+ // b. Repeat,
+ loop {
+ // i. Let value be ? IteratorStepValue(iterated).
+ let value = iterator_step_value(vm, &iterated)?;
+
+ // ii. If value is DONE, then
+ let Some(value) = value else {
+ // 1. If buffer is not empty, then
+ if !buffer.is_empty() {
+ // a. Perform Completion(Yield(CreateArrayFromList(buffer))).
+ return Ok(yield_value(Value::from_object(Array::create_from_list(
+ vm,
+ current_realm(vm),
+ &buffer,
+ ))));
+ }
+
+ // 2. Return ReturnCompletion(undefined).
+ return Ok(return_undefined());
+ };
+
+ // iii. Append value to buffer.
+ buffer.push(value);
+
+ // iv. If the number of elements in buffer is ℝ(chunkSize), then
+ if buffer.len() == chunk_size as usize {
+ // 1. Let completion be Completion(Yield(CreateArrayFromList(buffer))).
+ // 2. IfAbruptCloseIterator(completion, iterated).
+ // 3. Set buffer to a new empty List.
+ // NB: IteratorHelper handles abrupt completion, and the next call creates a new buffer.
+ return Ok(yield_value(Value::from_object(Array::create_from_list(
+ vm,
+ current_realm(vm),
+ &buffer,
+ ))));
+ }
+ }
+}
+
/// The closure of Iterator.prototype.drop, step 11.
pub fn drop_closure(
vm: &Vm,
diff --git a/Tests/LibJS/Runtime/builtins/Iterator/Iterator.prototype.chunks.js b/Tests/LibJS/Runtime/builtins/Iterator/Iterator.prototype.chunks.js
new file mode 100644
index 00000000000..cb270e8d0ef
--- /dev/null
+++ b/Tests/LibJS/Runtime/builtins/Iterator/Iterator.prototype.chunks.js
@@ -0,0 +1,224 @@
+describe("normal behavior", () => {
+ test("function properties", () => {
+ expect(Iterator.prototype.chunks).toHaveLength(1);
+ expect(Iterator.prototype.chunks.name).toBe("chunks");
+ expect(Object.getOwnPropertyDescriptor(Iterator.prototype, "chunks")).toEqual({
+ value: Iterator.prototype.chunks,
+ writable: true,
+ enumerable: false,
+ configurable: true,
+ });
+ });
+
+ test("chunks of different sizes", () => {
+ for (const [values, size, expected] of [
+ [[], 2, []],
+ [[1, 2, 3], 1, [[1], [2], [3]]],
+ [
+ [1, 2, 3, 4],
+ 2,
+ [
+ [1, 2],
+ [3, 4],
+ ],
+ ],
+ [[1, 2, 3, 4, 5], 2, [[1, 2], [3, 4], [5]]],
+ [[1, 2], 3, [[1, 2]]],
+ [[1, 2], 2 ** 32 - 1, [[1, 2]]],
+ [[undefined, null], 2, [[undefined, null]]],
+ ]) {
+ expect(values.values().chunks(size).toArray()).toEqual(expected);
+ }
+ });
+
+ test("iteration is lazy and reads next only once", () => {
+ let nextLookups = 0;
+ let nextCalls = 0;
+ const source = {
+ get next() {
+ ++nextLookups;
+ return function () {
+ expect(this).toBe(source);
+ expect(arguments).toHaveLength(0);
+ return { value: ++nextCalls, done: false };
+ };
+ },
+ [Symbol.iterator]() {
+ expect().fail("Symbol.iterator must not be called");
+ },
+ };
+ const iterator = Iterator.prototype.chunks.call(source, 2);
+ expect(nextLookups).toBe(1);
+ expect(nextCalls).toBe(0);
+ expect(iterator.next()).toEqual({ value: [1, 2], done: false });
+ expect(nextCalls).toBe(2);
+ expect(iterator.next()).toEqual({ value: [3, 4], done: false });
+ expect(nextLookups).toBe(1);
+ });
+
+ test("yielded arrays are independent", () => {
+ const value = {};
+ const iterator = [value, 2, 3].values().chunks(1);
+ const first = iterator.next().value;
+ first.push(42);
+ expect(iterator.next().value).toEqual([2]);
+ expect(iterator.next().value).toEqual([3]);
+ expect(first).toEqual([value, 42]);
+ });
+
+ test("return closes the underlying iterator before and after starting", () => {
+ for (const started of [false, true]) {
+ let returnCalls = 0;
+ const source = {
+ next() {
+ return { value: 1, done: false };
+ },
+ return() {
+ expect(this).toBe(source);
+ expect(arguments).toHaveLength(0);
+ ++returnCalls;
+ return {};
+ },
+ };
+ const iterator = Iterator.prototype.chunks.call(source, 2);
+ if (started) iterator.next();
+ expect(iterator.return()).toEqual({ value: undefined, done: true });
+ expect(iterator.next()).toEqual({ value: undefined, done: true });
+ iterator.return();
+ expect(returnCalls).toBe(1);
+ }
+ });
+
+ test("the final partial chunk does not advance or close an exhausted iterator", () => {
+ for (const close of [false, true]) {
+ let nextCalls = 0;
+ const source = {
+ next() {
+ ++nextCalls;
+ return { value: 42, done: nextCalls > 1 };
+ },
+ return() {
+ expect().fail("An exhausted iterator must not be closed");
+ },
+ };
+ const iterator = Iterator.prototype.chunks.call(source, 2);
+ expect(iterator.next()).toEqual({ value: [42], done: false });
+ expect(close ? iterator.return() : iterator.next()).toEqual({ value: undefined, done: true });
+ expect(iterator.next()).toEqual({ value: undefined, done: true });
+ expect(nextCalls).toBe(2);
+ }
+ });
+});
+
+describe("errors", () => {
+ test("receiver must be an object", () => {
+ for (const receiver of [undefined, null, false, 1, "abc", Symbol(), 1n]) {
+ expect(() => Iterator.prototype.chunks.call(receiver, 1)).toThrow(TypeError);
+ }
+ });
+
+ test("size must be an integral number without coercion", () => {
+ for (const size of [
+ undefined,
+ null,
+ true,
+ "2",
+ Symbol(),
+ 2n,
+ NaN,
+ Infinity,
+ -Infinity,
+ 1.5,
+ -0.5,
+ { valueOf: () => 2 },
+ ]) {
+ expect(() => [].values().chunks(size)).toThrowWithMessage(TypeError, "chunkSize is not an integral Number");
+ }
+ });
+
+ test("size must be in the array length range", () => {
+ for (const size of [0, -0, -1, 2 ** 32, Number.MAX_VALUE]) {
+ expect(() => [].values().chunks(size)).toThrowWithMessage(
+ RangeError,
+ "chunkSize must be between 1 and 2^32-1 inclusive"
+ );
+ }
+ });
+
+ test("validation closes the iterator before reading next and preserves the original error", () => {
+ for (const [size, error] of [
+ [undefined, TypeError],
+ [0, RangeError],
+ ]) {
+ let returnCalls = 0;
+ const source = {
+ get next() {
+ expect().fail("Validation must precede reading next");
+ },
+ return() {
+ ++returnCalls;
+ throw new Error("close failed");
+ },
+ };
+ expect(() => Iterator.prototype.chunks.call(source, size)).toThrow(error);
+ expect(returnCalls).toBe(1);
+ }
+ });
+
+ test("iterator protocol failures do not close the source", () => {
+ const failure = new Error("iteration failed");
+ for (const next of [
+ () => {
+ throw failure;
+ },
+ () => 1,
+ () => ({
+ get done() {
+ throw failure;
+ },
+ }),
+ () => ({
+ get value() {
+ throw failure;
+ },
+ }),
+ ]) {
+ const source = {
+ next,
+ return() {
+ expect().fail("A protocol failure must not close the source");
+ },
+ };
+ const iterator = Iterator.prototype.chunks.call(source, 2);
+ expect(() => iterator.next()).toThrow();
+ expect(iterator.next()).toEqual({ value: undefined, done: true });
+ iterator.return();
+ }
+ });
+
+ test("return propagates errors from the source", () => {
+ for (const started of [false, true]) {
+ const source = {
+ next: () => ({ value: 1, done: false }),
+ return() {
+ throw new Error("close failed");
+ },
+ };
+ const iterator = Iterator.prototype.chunks.call(source, 1);
+ if (started) iterator.next();
+ expect(() => iterator.return()).toThrowWithMessage(Error, "close failed");
+ }
+ });
+
+ test("helpers cannot be resumed while executing", () => {
+ const source = {
+ next() {
+ expect(() => iterator.next()).toThrow(TypeError);
+ expect(() => iterator.return()).toThrow(TypeError);
+ return { value: 1, done: false };
+ },
+ };
+ const iterator = Iterator.prototype.chunks.call(source, 1);
+ expect(iterator.next()).toEqual({ value: [1], done: false });
+ });
+});