Skip to content

Instantly share code, notes, and snippets.

@lightsofapollo
Created April 30, 2012 14:49
Show Gist options
  • Save lightsofapollo/2558934 to your computer and use it in GitHub Desktop.
Save lightsofapollo/2558934 to your computer and use it in GitHub Desktop.
generator hack for mocha tests (don't use this code)
var globals = [
'suiteSetup',
'test'
];
var Task = (function() {
var current, done;
return {
start: function(generator, cb) {
current = generator;
if (!current.next) {
current = generator.call(this);
}
done = cb;
if (current && current.next) {
current.next();
}
return this;
},
next: function(value) {
try {
current.send(value);
} catch (e) {
if (e instanceof StopIteration) {
done();
current = null;
done = null;
} else {
current = null;
done = null;
throw e;
done();
}
}
}
};
}());
globals.forEach(function(type) {
window['g' + type] = function() {
var orig = window[type];
var args = Array.prototype.slice.call(arguments),
cb = args.pop();
function wrapper(done) {
var gen, useDone = cb.length > 0;
if (useDone) {
gen = cb(done);
} else {
gen = cb();
}
if (gen.next) {
Task.start(gen, function() {
done();
});
} else {
if (!useDone) {
done();
}
}
}
wrapper.toString = function() {
return cb.toString();
}
args.push(wrapper);
orig.apply(window, args);
}
});
function complete(val) {
setTimeout(function() {
Task.next(val);
}, 250);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment