Last active
December 16, 2015 18:49
-
-
Save kpuputti/5480120 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 collectPairs(arr) { | |
return arr.reduce(function (acc, curr) { | |
var last = _.last(acc); | |
if (acc.length === 0 || last.length === 2) { | |
acc.push([curr]); | |
return acc; | |
} else { | |
last.push(curr); | |
return acc; | |
} | |
}, []); | |
} | |
collectPairs([]) // [] | |
collectPairs([1]) // [[1]] | |
collectPairs([1, 2]) // [[1, 2]] | |
collectPairs([1, 2, 3]) // [[1, 2], [3]] | |
collectPairs([1, 2, 3, 4, 5, 6]) // [[1, 2], [3, 4], [5, 6]] | |
collectPairs([1, 2, 3, 4, 5, 6, 7]) // [[1, 2], [3, 4], [5, 6], [7]] | |
// Using _.groupBy and _.zip | |
function zipPairs(arr) { | |
var parts = _.groupBy(arr, function (val, i) { | |
return i % 2 === 0 ? 'even' : 'odd'; | |
}); | |
return _.zip(parts.even || [], parts.odd || []); | |
} | |
zipPairs([]) // [] | |
zipPairs([1]) // [[1, undefined]] | |
zipPairs([1, 2]) // [[1, 2]] | |
zipPairs([1, 2, 3]) // [[1, 2], [3, undefined]] | |
// Original solution, generalized | |
function collectN(n, xs) { | |
return xs.reduce(function (acc, curr) { | |
var last = _.last(acc); | |
if (acc.length === 0 || last.length === n) { | |
acc.push([curr]); | |
} else { | |
last.push(curr); | |
} | |
return acc; | |
}, []); | |
} | |
var pairs = collectN.bind(null, 2); // partial application ftw | |
pairs([]) // [] | |
pairs([1, 2, 3, 4, 5, 6]) // [[1, 2], [3, 4], [5, 6]] | |
pairs([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
@pyrtsa Cool!