Skip to content

Instantly share code, notes, and snippets.

@fersilva16
Last active December 14, 2021 23:15
Show Gist options
  • Save fersilva16/80883e009f4b5d05824700709ef97d37 to your computer and use it in GitHub Desktop.
Save fersilva16/80883e009f4b5d05824700709ef97d37 to your computer and use it in GitHub Desktop.
Chunk array by n length
function chunk(n: number, xs: number[]) {
if (!xs.length) return [];
return [xs.slice(0, n), ...chunk(n, xs.slice(n))];
}
@fersilva16
Copy link
Author

fersilva16 commented Dec 14, 2021

Using anonymous function:

const chunk = (n: number, xs: number[]) => !xs.length ? [] : [xs.slice(0, n), ...chunk(n, xs.slice(n))];

@fersilva16
Copy link
Author

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