Skip to content

Instantly share code, notes, and snippets.

@harbirchahal
Created May 17, 2021 08:11
Show Gist options
  • Save harbirchahal/4f96749ce2f2ad96275ec6ffd2c82a18 to your computer and use it in GitHub Desktop.
Save harbirchahal/4f96749ce2f2ad96275ec6ffd2c82a18 to your computer and use it in GitHub Desktop.
ES6: Buffer Iterator
function BufferIterator(collection, bufferSize) {
this[Symbol.iterator] = function () {
let nextIndex = 0;
return {
next: () => {
if (nextIndex < collection.length) {
const buffer = new Array(bufferSize);
for (let i = 0; i < bufferSize; i++) {
buffer[i] = collection[nextIndex++];
}
return { value: buffer, done: false };
}
return { done: true };
},
};
};
}
// Main
const arr = [1, 2, 3, 4, 5, 6];
for(let buff of new BufferIterator(arr, 2)) {
console.log(buff);
}
//-> [1, 2] [3, 4] [5, 6]
for(let buff of new BufferIterator(arr, 3)) {
console.log(buff);
}
//-> [1, 2, 3] [4, 5, 6]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment