Skip to content

Instantly share code, notes, and snippets.

@mariusGundersen
Last active August 29, 2015 14:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mariusGundersen/9695efb270b9a5a056eb to your computer and use it in GitHub Desktop.
Save mariusGundersen/9695efb270b9a5a056eb to your computer and use it in GitHub Desktop.
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