Parallelization made easy in JavaScript / Node.js
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');
});
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).