Skip to content

Instantly share code, notes, and snippets.

@pyrtsa
Created April 29, 2013 07:16
Show Gist options
  • Save pyrtsa/5480171 to your computer and use it in GitHub Desktop.
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.
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]]
@kpuputti
Copy link

The more I look at this, the more I like its simplicity.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment