Skip to content

Instantly share code, notes, and snippets.

@sliminality
Created August 3, 2016 20:07
Show Gist options
  • Save sliminality/10c45b6d608275ce343e4f43d79c8e1c to your computer and use it in GitHub Desktop.
Save sliminality/10c45b6d608275ce343e4f43d79c8e1c to your computer and use it in GitHub Desktop.
chunk an array of numbers
const chunker = (partial, current) => {
const end = partial.length - 1;
if (end >= 0 && current === partial[end][0]) {
return [
...partial.slice(0, end),
[...partial[end], current]
];
}
return [...partial, [current]];
};
console.log(
JSON.stringify(
[1, 1, 1, 2, 3, 3].reduce(chunker, [])
) === '[[1,1,1],[2],[3,3]]'
);
console.log(
JSON.stringify(
[1, 1, 2, 2, 1, null, 2, 2].reduce(chunker, [])
) === '[[1,1],[2,2],[1],[null],[2,2]]'
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment