Skip to content

Instantly share code, notes, and snippets.

@kpuputti
Last active December 16, 2015 18:49
Show Gist options
  • Save kpuputti/5480120 to your computer and use it in GitHub Desktop.
Save kpuputti/5480120 to your computer and use it in GitHub Desktop.
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]]
@kpuputti
Copy link
Author

@pyrtsa Cool!

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