Last active
December 14, 2021 23:15
-
-
Save fersilva16/80883e009f4b5d05824700709ef97d37 to your computer and use it in GitHub Desktop.
Chunk array by n length
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(n: number, xs: number[]) { | |
if (!xs.length) return []; | |
return [xs.slice(0, n), ...chunk(n, xs.slice(n))]; | |
} |
Chunk by n length, but repeating items:
function chunk(n: number, xs: number[]) {
if (xs.length > n) return [];
return [xs.slice(0, n), ...chunk(n, xs.slice(1))];
}
Using anonymous function:
const chunk = (n: number, xs: number[]) => xs.length < n ? [] : [xs.slice(0, n), ...chunk(n, xs.slice(1))];
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Using anonymous function: