Last active
May 11, 2017 16:59
-
-
Save jennings/e481206e8ee5d42418fd71bca816c062 to your computer and use it in GitHub Desktop.
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 Enumerable(arr) { | |
this.toArray = function () { | |
return arr | |
} | |
this.filter = function (fn) { | |
return new Enumerable(arr.filter(fn)) | |
} | |
this.map = function (fn) { | |
return new Enumerable(arr.map(fn)) | |
} | |
this.flatMap = function (fn) { | |
return new Enumerable(_.flatMap(arr, fn)) | |
} | |
} | |
var a = [ [1,2], [3,4,5], [6,7] ] | |
var a = [ [11,12], [13,14,15], [16,17] ] | |
new Enumerable(a) | |
.filter(function (a) { return a.length % 2 == 0 }) | |
.flatMap() //=> [1, 2, 6, 7] | |
// Or, just add _.flatMap to Array's prototype: | |
// Array.prototype.flatMap = function (fn) { return _.flatMap(this, fn) } | |
// Build a pipeline that can be applied to different inputs | |
var pipeline = Enumerable | |
.filter(function (a) { return a.length % 2 == 0 }) | |
.flatMap() | |
// Mostly equivalent to: | |
// pipeline = function (input) { | |
// return Enumerable(input) | |
// .filter(function (a) { return a.length % 2 == 0 }) | |
// .flatMap() | |
// } | |
pipeline.toString() //=> filter(fn.name) | flatMap() | |
pipeline(a) //=> [1, 2, 6, 7] | |
pipeline(b) //=> [11, 12, 16, 17] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment