Created
March 26, 2021 00:31
-
-
Save friendlyanon/5497819e936377a71f0f1c4aa8dea241 to your computer and use it in GitHub Desktop.
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* chunkIterable(iterable, chunkSize) { | |
const it = iterable[Symbol.iterator](); | |
for (let i = 0; i !== -1; ) { | |
const chunk = []; | |
for (const limit = i + chunkSize; i < limit; ++i) { | |
const { done, value } = it.next(); | |
if (done) { | |
i = -1; | |
break; | |
} | |
chunk.push(value); | |
} | |
yield chunk; | |
} | |
} | |
function* chunkArray(array, chunkSize) { | |
const limit = array.length; | |
for (let i = 0; i < limit; i += chunkSize) { | |
yield array.slice(i, i + chunkSize); | |
} | |
} | |
function chunk(iterable, chunkSize) { | |
if (!(chunkSize > 0)) { | |
return [].values(); | |
} | |
return Array.isArray(iterable) | |
? chunkArray(iterable, chunkSize) | |
: chunkIterable(iterable, chunkSize); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment