Skip to content

Instantly share code, notes, and snippets.

@jennings
Last active May 11, 2017 16:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jennings/e481206e8ee5d42418fd71bca816c062 to your computer and use it in GitHub Desktop.
Save jennings/e481206e8ee5d42418fd71bca816c062 to your computer and use it in GitHub Desktop.
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