Skip to content

Instantly share code, notes, and snippets.

@snowmantw
Last active August 29, 2015 14:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save snowmantw/26777b20e5782c63e915 to your computer and use it in GitHub Desktop.
Save snowmantw/26777b20e5782c63e915 to your computer and use it in GitHub Desktop.
It's a reducer, actually
// "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