Last active
December 27, 2015 15:29
-
-
Save animatedlew/7348093 to your computer and use it in GitHub Desktop.
Here is a mix of imperative and functional programming.
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 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