Skip to content

Commit

Permalink
Draft parallel implementation.
Browse files Browse the repository at this point in the history
  • Loading branch information
tmpfs committed Mar 19, 2016
1 parent 329f49d commit 41d15ca
Show file tree
Hide file tree
Showing 2 changed files with 97 additions and 1 deletion.
62 changes: 61 additions & 1 deletion runner.js
Original file line number Diff line number Diff line change
Expand Up @@ -71,9 +71,58 @@ function series(list, cb) {
next();
}

/**
* Execute task functions in parallel.
*
* @function parallel
* @member Runner
* @param {Array} list of task functions.
* @param {Number} [concurrent] number of concurrent calls.
* @param {Function} cb callback function.
*/
function parallel(list, concurrent, cb) {
if(concurrent instanceof Function) {
cb = concurrent;
concurrent = 0;
}

var items = list.slice()
, scope = this.scope
, complete = 0;

concurrent = concurrent || items.length;

function run() {
for(var i = 0;i < concurrent;i++) {
items[i].call(scope, next);
}
items = items.slice(concurrent);
}

function next(err) {
if(err) {
return cb(err);
}

complete++;

if(complete >= list.length) {
return cb();
}

if(items.length && (complete % concurrent === 0)) {
run();
}
}

run();
}

/**
* Execute a task by name identifier.
*
* Dependencies are run in parallel before task execution.
*
* @function exec
* @member Runner
* @param {Function|String} id task identifier.
Expand All @@ -88,13 +137,24 @@ function exec(id, cb) {
throw new Error('task not found: ' + id);
}

this.series(task.tasks, cb);
function onDependencies(err) {
if(err) {
return cb(err);
}
this.series(task.tasks, cb);
}

if(task.deps.length) {
this.parallel(task.deps, onDependencies.bind(this));
}else{
this.series(task.tasks, cb);
}
return task;
}

Runner.prototype.get = get;
Runner.prototype.exec = exec;
Runner.prototype.series = series;
Runner.prototype.parallel = parallel;

module.exports = runner;
36 changes: 36 additions & 0 deletions test/spec/run.js
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,42 @@ describe('mktask:', function() {
});
});

it('should exec task functions dependencies in parallel', function(done) {
var mk = mktask()
, called = 0
, docsCalled
, apiCalled
, readmeCalled;

function docs(cb) {
called++;
docsCalled = 1;
cb();
}

function api(cb) {
called++;
apiCalled = 1;
cb();
}

function readme(cb) {
called++;
readmeCalled = 1;
cb();
}

mk.task([docs, api], readme);

var runner = mk.run();
runner.exec(readme, function() {
expect(called).to.eql(3);
expect(docsCalled).to.eql(1);
expect(apiCalled).to.eql(1);
expect(readmeCalled).to.eql(1);
done();
});
});

it('should callback with error on task function exec', function(done) {
var mk = mktask()
Expand Down

0 comments on commit 41d15ca

Please sign in to comment.