Last active
August 29, 2015 14:27
-
-
Save snowmantw/26777b20e5782c63e915 to your computer and use it in GitHub Desktop.
It's a reducer, actually
This file contains 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
// "pure" version | |
[1, 2, 3, 4].reduce(function(acc, elem) { | |
var result = []; | |
// Generate multiple "elements". | |
for (var i = 0; i < elem; i++) { | |
result.push(i); | |
} | |
// And generate the new "array" as the new accumulator. | |
return acc.concat(result); | |
}, []) | |
// "impure" version | |
[1, 2, 3, 4].reduce(function(acc, elem) { | |
var result = []; | |
// Generate multiple "elements". | |
for (var i = 0; i < elem; i++) { | |
acc.push(i); | |
} | |
// remember to return it! | |
return acc; | |
}, []) | |
// lo-dash named it as: _.flatten: | |
// https://lodash.com/docs#flatten | |
var theNestedArray = (function(arr){ | |
return arr.map(function(elem) { | |
var result = []; | |
for (var i = 0; i < elem; i++) { | |
result.push(i); | |
} | |
return result; | |
}); | |
})([1,2,3,4]) | |
_.flatten(theNestedArray, true); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment