Last active
August 25, 2023 16:43
-
-
Save christophemarois/c471605b8c3c150e086319aaeec73f17 to your computer and use it in GitHub Desktop.
Chunking arrays and strings in typescript
This file contains 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 chunk<T>(arr: T[], size: number): T[][] { | |
const count = Math.ceil(arr.length / size) | |
let out: T[][] = [] | |
for (let i = 0; i < count; i++) { | |
out.push(arr.slice(count * i, count * (i + 1))) | |
} | |
return out | |
} | |
function chunkString(str: string, size: number): string[] { | |
return chunk(str.split(''), size).map((part) => part.join('')) | |
} | |
chunkString('abcdefg', 4) | |
// iterable version | |
function* chunkIter(size: number, arr: T[]): IterableIterator<T[]> { | |
for (let i = 0; i < arr.length; i += size) { | |
yield arr.slice(i, i + size) | |
} | |
} | |
// simpler alternative? | |
function chunk<T>(size: number, arr: T[]): T[][] { | |
let chunks: T[][] = [] | |
for (let i = 0; i < arr.length; i += size) { | |
chunks.push(arr.slice(i, i + size)) | |
} | |
return chunks | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment