Stage 1 Draft / September 18, 2024

Iterator Chunking

1 Iterator.prototype.chunks ( chunkSize )

This method performs the following steps when called:

  1. Let O be the this value.
  2. If O is not an Object, throw a TypeError exception.
  3. If chunkSize is not an integral Number in the inclusive interval from 1𝔽 to 𝔽(232 - 1), throw a RangeError exception.
  4. Let iterated be ? GetIteratorDirect(O).
  5. Let closure be a new Abstract Closure with no parameters that captures iterated and chunkSize and performs the following steps when called:
    1. Let buffer be a new empty List.
    2. Repeat,
      1. Let value be ? IteratorStepValue(iterated).
      2. If value is done, then
        1. If buffer is not empty, then
          1. Perform Completion(Yield(CreateArrayFromList(buffer))).
        2. Return NormalCompletion(unused).
      3. Append value to buffer.
      4. If the number of elements in buffer is (chunkSize), then
        1. Let completion be Completion(Yield(CreateArrayFromList(buffer))).
        2. IfAbruptCloseIterator(completion, iterated).
        3. Set buffer to a new empty List.
  6. Let result be CreateIteratorFromClosure(closure, "Iterator Helper", %IteratorHelperPrototype%, « [[UnderlyingIterators]] »).
  7. Set result.[[UnderlyingIterators]] to « iterated ».
  8. Return result.

2 Iterator.prototype.windows ( windowSize )

This method performs the following steps when called:

  1. Let O be the this value.
  2. If O is not an Object, throw a TypeError exception.
  3. If windowSize is not an integral Number in the inclusive interval from 1𝔽 to 𝔽(232 - 1), throw a RangeError exception.
  4. Let iterated be ? GetIteratorDirect(O).
  5. Let closure be a new Abstract Closure with no parameters that captures iterated and windowSize and performs the following steps when called:
    1. Let buffer be a new empty List.
    2. Repeat,
      1. Let value be ? IteratorStepValue(iterated).
      2. If value is done, return NormalCompletion(unused).
      3. Append value to buffer.
      4. If the number of elements in buffer is (windowSize), then
        1. Let completion be Completion(Yield(CreateArrayFromList(buffer))).
        2. IfAbruptCloseIterator(completion, iterated).
        3. Remove the first element from buffer.
  6. Let result be CreateIteratorFromClosure(closure, "Iterator Helper", %IteratorHelperPrototype%, « [[UnderlyingIterators]] »).
  7. Set result.[[UnderlyingIterators]] to « iterated ».
  8. Return result.