Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Cleaned up the architecture a bit

  • Loading branch information...
commit 4d98fae8a80df64da56d64286f7c6ee4eff130a0 1 parent 2cd34b0
@DanielBaulig authored
Showing with 16 additions and 21 deletions.
  1. +16 −21 lib/first.js
View
37 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
@@ -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;
}
};

0 comments on commit 4d98fae

Please sign in to comment.
Something went wrong with that request. Please try again.