Skip to content

Instantly share code, notes, and snippets.

@alucky0707
Created September 23, 2013 06:07
Show Gist options
  • Save alucky0707/6666936 to your computer and use it in GitHub Desktop.
Save alucky0707/6666936 to your computer and use it in GitHub Desktop.
JavaScriptにもflatMapを! ref: http://qiita.com/alucky0707/items/88bd35208b12243768ac
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] : [];
}));
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());
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