Skip to content

Instantly share code, notes, and snippets.

@pixelis0x
Last active January 27, 2017 13:31
Show Gist options
  • Select an option

  • Save pixelis0x/c7862a7779e31af673847db60df39a21 to your computer and use it in GitHub Desktop.

Select an option

Save pixelis0x/c7862a7779e31af673847db60df39a21 to your computer and use it in GitHub Desktop.
//implement missing "Parallel" please
//try to do so with a minimal amount of code
//implementation
function Parallel({paralelJob}) {
this.paralelJob = paralelJob;
this.results = [];
this.calledCounter = 0;
this.totalCounter = 0;
}
Parallel.prototype.done = function(callback) {
setTimeout(function tick(self) {
if (!self.calledCounter) {
callback(self.results);
} else {
setTimeout(tick, 0, self);
}
}, 0, this);
}
Parallel.prototype.complete = function complete(counter, result) {
console.log(result + ' completed')
this.results[counter] = result;
--this.calledCounter;
};
Parallel.prototype.job = function job(callback) {
setTimeout(function jobApply(self){
if (self.calledCounter < self.paralelJob) {
callback(self.complete.bind(self, self.totalCounter++));
++self.calledCounter;
} else {
setTimeout(jobApply, 0, self)
}}, 0, this);
return this;
};
//check calls
var runner = new Parallel({
paralelJob: 2
});
runner.job(step1)
.job(step2)
.job(step3)
.job(step4)
.done(onDone);
function step1(done) {
console.log('step1');
setTimeout(done, 100, 'step1');
}
function step2(done) {
console.log('step2');
setTimeout(done, 10, 'step2');
}
function step3(done) {
console.log('step3');
setTimeout(done, 150, 'step3');
}
function step4(done) {
console.log('step4');
setTimeout(done, 50, 'step4');
}
function onDone(results) {
console.log(results);
console.assert(Array.isArray(results), 'expect result to be array');
console.assert(results[0] === 'step1', 'Wrong answer 1');
console.assert(results[1] === 'step2', 'Wrong answer 2');
console.assert(results[2] === 'step3', 'Wrong answer 3');
console.assert(results[3] === 'step4', 'Wrong answer 4');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment