Created
September 23, 2013 06:07
-
-
Save alucky0707/6666936 to your computer and use it in GitHub Desktop.
JavaScriptにもflatMapを! ref: http://qiita.com/alucky0707/items/88bd35208b12243768ac
This file contains hidden or 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 flatMap(xs, f) { | |
return xs.reduce(function (ys, x) { | |
return ys.concat(f(x)); | |
}, []); | |
} | |
//=> [4, 12, 20, 28, 36] | |
console.log(flatMap([1,2,3,4,5,6,7,8,9,10], function (x) { | |
return x % 2 === 1 ? [x << 2] : []; | |
})); |
This file contains hidden or 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
var | |
_ = require('underscore'); | |
var | |
flatMap = _.flatMap = _.concatMap = function (xs, f, self) {; | |
return _.reduce(xs, function (ys, x) { | |
return ys.concat(f.call(self, x)); | |
}, []); | |
}; | |
_.each(['flatMap', 'concatMap'], function (name) { | |
_.prototype[name] = function (f, self) { | |
return _(flatMap(this.value(), f, self)); | |
}; | |
}); | |
//さっきよりシンプルになったように見えるのは_.rangeのおかげ? | |
console.log(_.flatMap(_.range(1, 11), function (x) { | |
return x % 2 === 1 ? [x << 2] : []; | |
})); | |
//こういう風にも書ける | |
console.log(_(_.range(1, 11)).flatMap(function (x) { | |
return x % 2 === 1 ? [x << 2] : []; | |
}).value()); |
This file contains hidden or 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
Object.defineProperty(Array.prototype, 'flatMap', { | |
value: function (f, self) { | |
self = self || this; | |
return this.reduce(function (ys, x) { | |
return ys.concat(f.call(self, x)); | |
}, []); | |
}, | |
enumerable: false, | |
}); | |
//=> [4, 12, 20, 28, 36] | |
console.log([1,2,3,4,5,6,7,8,9,10].flatMap(function (x) { | |
return x % 2 === 1 ? [x << 2] : []; | |
})); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment