Skip to content

Instantly share code, notes, and snippets.

@sstephenson
Created February 25, 2009 19:20
Show Gist options
  • Save sstephenson/70357 to your computer and use it in GitHub Desktop.
Save sstephenson/70357 to your computer and use it in GitHub Desktop.
var BackgroundIteration = Class.create({
initialize: function(iterator, produceNextValue) {
this.iterator = iterator;
this.produceNextValue = produceNextValue;
this.callbacks = [];
this.results = [];
this.next = this.next.bind(this);
this.next.defer();
},
next: function() {
var value = {}, hasValue = this.produceNextValue(value);
this.running = true;
if (hasValue) {
try {
this.results.push(this.iterator(value.value));
this.next.defer();
} catch (exception) {
this.exception = exception;
this.end();
}
} else {
this.end();
}
},
end: function() {
if (this.running) {
this.running = false;
this.callbacks.invoke("call", this);
}
},
after: function(callback) {
this.callbacks.push(callback);
return this;
}
});
Object.extend(Array.prototype, {
backgroundEach: function(iterator) {
var index = 0;
return new BackgroundIteration(iterator, function(memo) {
if (index == this.length) {
return false;
} else {
memo.value = this[index++];
return true;
}
}.bind(this));
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment