Skip to content

Commit

Permalink
Cleaned up the architecture a bit
Browse files Browse the repository at this point in the history
  • Loading branch information
Daniel Baulig committed Mar 17, 2012
1 parent 2cd34b0 commit 4d98fae
Showing 1 changed file with 16 additions and 21 deletions.
37 changes: 16 additions & 21 deletions lib/first.js
@@ -1,26 +1,16 @@
/*jshint eqeqeq:true, proto:true, laxcomma:true, undef:true, node:true, expr: true, boss:true*/
/*jshint eqeqeq:true, proto:true, laxcomma:true, undef:true, node:true, expr: true*/

var slice = Array.prototype.slice;
var slice = Array.prototype.slice, isArray = require('util').isArray;

module.exports = function first (f) {
var functions = [{f: f}], next = function () {
var f, p = [];
var functions = [f], next = function () {
var f = functions.shift(), p = [];

// get the first function
if (f = functions.shift()) {
p.push(f);
} else {
return;
}

// keep getting functions with the p flag set (parallelize)
while(functions[0] && functions[0].p) {
p.push(functions.shift());
}
if (!f) return;

// if there more than one function to run in parallel
if (p.length > 1) {
var i = p.length
if (isArray(f)) {
var i = f.length
, n = i
, results = []
// bucket creates a callback, that counts how often it was called
Expand All @@ -42,23 +32,28 @@ module.exports = function first (f) {
while(i--) {
// now run all functions simultaniously, giving them their respective
// bucket and the arguments that where given to this call to next.
p[i].f.apply(bucket(i), arguments);
f[i].apply(bucket(i), arguments);
}

} else {
// if there's only one, simply run it, giving it next as this
// and the arguments given to this call to next as arguments.
p[0].f.apply(next, arguments);
f.apply(next, arguments);
}
};

var deferred = {
then: function(f) {
functions.push({f: f});
functions.push(f);
return this;
},
whilst: function(f) {
functions.push({f: f, p: true});
var last = functions.length-1;
if (isArray (functions[last])) {
functions[last].push(f);
} else {
functions[last] = [functions[last], f];
}
return this;
}
};
Expand Down

0 comments on commit 4d98fae

Please sign in to comment.