Skip to content

Instantly share code, notes, and snippets.

@animatedlew
Last active December 27, 2015 15:29
Show Gist options
  • Save animatedlew/7348093 to your computer and use it in GitHub Desktop.
Save animatedlew/7348093 to your computer and use it in GitHub Desktop.
Here is a mix of imperative and functional programming.
function unflatten(list, group) {
var result = [];
for (var j = 0; j < Math.ceil(list.length/group); j++) {
for (var i = 0, sublist = [], cache = list[i+(j*group)]; i < group; i++) {
cache ? sublist.push(cache) : sublist;
}
result.push(sublist);
}
return result;
}
console.log(unflatten(_.range(1, 15), 4));
// [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
console.log(_.chain(unflatten(_.range(1, 11), 3))
// Grab each sublist and...
.map(function(sublist) {
// Sum each of its elements up!
return _.reduce(sublist, function(total, num) {
return total += num;
});
}).value());
// [6, 15, 24, 10]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment