Stage 2 Draft / May 22, 2025
Iterator Chunking
1 Iterator.prototype.chunks ( chunkSize )
This method performs the following steps when called:
- Let O be the this value.
- If O is not an Object, throw a TypeError exception.
- Let iterated be the Iterator Record { [[Iterator]]: O, [[NextMethod]]: undefined, [[Done]]: false }.
- If chunkSize is not an integral Number in the inclusive interval from 1𝔽 to 𝔽(232 - 1), then
- Let error be ThrowCompletion(a newly created RangeError object).
- Return ? IteratorClose(iterated, error).
- Set iterated to ? GetIteratorDirect(O).
- Let closure be a new Abstract Closure with no parameters that captures iterated and chunkSize and performs the following steps when called:
- Let buffer be a new empty List.
- Repeat,
- Let value be ? IteratorStepValue(iterated).
- If value is done, then
- If buffer is not empty, then
- Perform Completion(Yield(CreateArrayFromList(buffer))).
- Return ReturnCompletion(undefined).
- Append value to buffer.
- If the number of elements in buffer is ℝ(chunkSize), then
- Let completion be Completion(Yield(CreateArrayFromList(buffer))).
- IfAbruptCloseIterator(completion, iterated).
- Set buffer to a new empty List.
- Let result be CreateIteratorFromClosure(closure, "Iterator Helper", %IteratorHelperPrototype%, « [[UnderlyingIterators]] »).
- Set result.[[UnderlyingIterators]] to « iterated ».
- Return result.
2 Iterator.prototype.windows ( windowSize )
This method performs the following steps when called:
- Let O be the this value.
- If O is not an Object, throw a TypeError exception.
- Let iterated be the Iterator Record { [[Iterator]]: O, [[NextMethod]]: undefined, [[Done]]: false }.
- If windowSize is not an integral Number in the inclusive interval from 1𝔽 to 𝔽(232 - 1), then
- Let error be ThrowCompletion(a newly created RangeError object).
- Return ? IteratorClose(iterated, error).
- Set iterated to ? GetIteratorDirect(O).
- Let closure be a new Abstract Closure with no parameters that captures iterated and windowSize and performs the following steps when called:
- Let buffer be a new empty List.
- Repeat,
- Let value be ? IteratorStepValue(iterated).
- If value is done, return ReturnCompletion(undefined).
- Append value to buffer.
- If the number of elements in buffer is ℝ(windowSize), then
- Let completion be Completion(Yield(CreateArrayFromList(buffer))).
- IfAbruptCloseIterator(completion, iterated).
- Remove the first element from buffer.
- Let result be CreateIteratorFromClosure(closure, "Iterator Helper", %IteratorHelperPrototype%, « [[UnderlyingIterators]] »).
- Set result.[[UnderlyingIterators]] to « iterated ».
- Return result.