Skip to content

Instantly share code, notes, and snippets.

@zhangchiqing
Last active July 16, 2016 22:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save zhangchiqing/1874f4c1d63ae82be80a to your computer and use it in GitHub Desktop.
Save zhangchiqing/1874f4c1d63ae82be80a to your computer and use it in GitHub Desktop.
flatMap.js
/*
* 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