Created
August 3, 2016 20:07
-
-
Save sliminality/10c45b6d608275ce343e4f43d79c8e1c to your computer and use it in GitHub Desktop.
chunk an array of numbers
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
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