Created
May 17, 2021 08:11
-
-
Save harbirchahal/4f96749ce2f2ad96275ec6ffd2c82a18 to your computer and use it in GitHub Desktop.
ES6: Buffer Iterator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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