Last active
August 29, 2015 14:05
-
-
Save mariusGundersen/9695efb270b9a5a056eb 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 Lazy(list, ...steps){ | |
this.list = list; | |
this.steps = steps; | |
} | |
Lazy.prototype.map = function(f){ | |
return new Lazy(this.list, ...this.steps, iteration | |
=> ( for (entry of iteration) f(entry))); | |
} | |
Lazy.prototype.takeUntil = function(f){ | |
return new Lazy(this.list, ...this.steps, function*(iteration){ | |
for (var entry of iteration){ | |
yield entry; | |
if(f(entry)) break; | |
} | |
}); | |
} | |
Lazy.prototype.toArray = function(){ | |
var steps = this.steps; | |
var previousStep = (for (entry of this.list) entry); | |
for(var nextStep of steps){ | |
previousStep = nextStep(previousStep); | |
} | |
return [for (x of previousStep) x]; | |
} | |
Lazy.extend = function(name, generator){ | |
Lazy.prototype[name] = function(f){ | |
return new Lazy(this.list, ...this.steps, generator.bind(f)); | |
} | |
} | |
new Lazy([1,2,3,4,5,6,7,8,9,10]).map(x => x*x).takeUntil(x => x==25).toArray(); | |
Lazy.extend('skipWhile', function*(iteration){ | |
var isSkipping = true; | |
for(var entry of iteration){ | |
if(isSkipping && this(entry)) continue; | |
isSkipping = false; | |
yield entry; | |
} | |
}); | |
new Lazy([1,2,3,4,5,6,7,8,9,10]).skipWhile(x => x<3).map(x => x*x).takeUntil(x => x==25).toArray();//[9, 16, 25] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment