Skip to content

Instantly share code, notes, and snippets.

@nijikokun
Last active August 29, 2015 13:55
Show Gist options
  • Save nijikokun/8745849 to your computer and use it in GitHub Desktop.
Save nijikokun/8745849 to your computer and use it in GitHub Desktop.
Javascript parallelization explained using cars and roads, because people have a hard time understanding things.

Road.js

Parallelization made easy in JavaScript / Node.js

Usage

var road = new Road();

road.onClear(function (error, results) { 
  console.log('The road is clear!', error, results); 
});

road.add(function first (turn) {

  road.add(function second (leave) {
    leave(null, '2');
  });
  
  turn(null, '1');
});

What's going on?

Well, first we created the road, added some cars to the road. Every time a car is added the number of cars on the road goes up (just as in memory the number of methods being executed is going up), these cars are driving either next to each other or just behind, upon their callback (turn and leave, which are the same method, just unique to that car) being made the car exits or turns off the road and the number of cars on the road goes down. We also save the results in the position that the car turned into on the road (you could alter the code to easily make it so it appears the cars are speeding up and down and put the results in the order of which you recieve them!).

When the number of cars or a crash happens (error) the road is declared to be cleared and returns the results (both the crash data, and the car data).

// road.js v0.1
//
// Copyright Nijiko Yonskai 2013
// License MIT
function Road () {
this.cars = 0;
this.turned = [];
this.cleared = false;
}
Road.prototype.add = function (method) {
var road = this;
var position = this.cars;
var turning = function (error, results) {
if (road.cleared) return;
if (error) return road.clear(error);
// ;) Tip: If you would rather get data back in the order of recieving use road.turned.pushed(results) instead!
road.turned[position] = results;
road.cars -= 1;
if (road.cars === 0) return road.clear(null);
};
this.cars += 1;
method(function () {
var args = arguments;
setTimeout(function() { // or nextTick in Node.JS, seriously use nextTick there.
turning.apply(null, args);
}, 25);
});
};
Road.prototype.onClear = function (callback) {
if (this.cars.length < 1)
return callback.apply();
var road = this;
this.clear = function (error) {
road.cleared = true;
return callback(error, road.turned);
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment