Created
August 9, 2016 01:46
-
-
Save dengjonathan/ff1366f856e86a640d2607338366260a to your computer and use it in GitHub Desktop.
flatten using reduce
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
function each(collection, callback) { | |
if (Array.isArray(collection)) { | |
for (var i = 0; i < collection.length; i++) { | |
callback(collection[i]); | |
} | |
} else { | |
for (var j in collection) { | |
callback(collection[j]); | |
} | |
} | |
} | |
function reduce(collection, callback, initial) { | |
var initialFlag = arguments.length < 3? false : true; | |
each(collection, function (e) { | |
if (!initialFlag) { | |
initial = e; | |
initialFlag = true; | |
} else { | |
initial = callback(initial, e); | |
} | |
return initial; | |
}); | |
return initial; | |
} | |
function flattenReduce(array) { | |
// on each call of flattenReduce return array transformed to flattened array | |
return reduce(array, function(total, curr){ | |
// if value is not an array, you can just push to total | |
if (!Array.isArray(curr)) { | |
total.push(curr); | |
} else { | |
// transform current value to flattened array with recursive call | |
curr = flattenReduce(curr); | |
// flattenReduce returns flat array | |
// for each value in flattened array, push to total | |
each(curr, function(e) {total.push(e);}) | |
} | |
return total; | |
}, []); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment