Created
April 29, 2013 07:16
-
-
Save pyrtsa/5480171 to your computer and use it in GitHub Desktop.
Split a sequence into groups of `n` consecutive elements each, with 1..n items in the last group.
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 range(n) { | |
return Array.apply(null, Array(n)).map(function (_, i) { return i }) | |
} | |
function ntuples(n, xs) { | |
return range(Math.ceil(xs.length / n)).map(function (i) { | |
return xs.slice(i * n, i * n + n) | |
}) | |
} | |
ntuples(2, 'abc') //=> ['ab', 'c'] | |
ntuples(2, 'abcdef') //=> ['ab', 'cd', 'ef'] | |
ntuples(3, [1, 2, 3, 4, 5, 6, 7]) //=> [[1, 2, 3], [4, 5, 6], [7]] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The more I look at this, the more I like its simplicity.