Last active
July 16, 2016 22:15
-
-
Save zhangchiqing/1874f4c1d63ae82be80a to your computer and use it in GitHub Desktop.
flatMap.js
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
/* | |
* flatMap can be implemented in terms of flatten and map | |
* which can be implemented using reduce | |
*/ | |
'use strict'; | |
// > reduce(function(sum, value) { return sum + value; }, | |
// . 0, [1,2,3]) | |
// 6 | |
var reduce = function(iter, initial, arr) { | |
if (!arr.length) { | |
return initial; | |
} | |
var newInitial = iter(initial, arr[0]); | |
return reduce(iter, newInitial, arr.slice(1)); | |
}; | |
// > map(function(a) { return a + 1; }, [1, 2, 3]) | |
// [2, 3, 4] | |
// > map(function(a) { return a; }, []) | |
// [] | |
var map = function(f, arr) { | |
return reduce(function(memo, item) { | |
return memo.concat([f(item)]); | |
}, [], arr); | |
}; | |
// > concat([1, 2, 3], [4, 5, 6]); | |
// [1, 2, 3, 4, 5, 6] | |
var concat = function(arr1, arr2) { | |
return reduce(function(memo, item) { | |
return memo.concat([item]); | |
}, arr1, arr2); | |
}; | |
// > flatten([[1], [2, 3], [4, 5, 6]]) | |
// [1, 2, 3, 4, 5, 6] | |
var flatten = function(arrs) { | |
return reduce(concat, [], arrs); | |
}; | |
// > flatMap(function(x) { | |
// . return [x, x + 1, x + 2]; | |
// . }, [1, 2, 3]); | |
// [1, 2, 3, 2, 3, 4, 3, 4, 5] | |
var flatMap = function(f, arr) { | |
return flatten(map(f, arr)); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment