Skip to content

Instantly share code, notes, and snippets.

@sheremetyev
Created February 22, 2011 14:38
Show Gist options
  • Save sheremetyev/838755 to your computer and use it in GitHub Desktop.
Save sheremetyev/838755 to your computer and use it in GitHub Desktop.
Matching problem in JavaScript
// Problem from Concurrent Programming course exercises
// Two kinds of processes Man and Woman pair off with the help of a Matcher
function random(max) {
return Math.floor(Math.random()*max);
}
function Man(name) {
setTimeout(function run() {
matcher.Man(name, function(pair) {
console.log(name + ' paired off with ' + pair);
setTimeout(run, random(1000));
});
}, random(1000));
}
function Woman(name) {
setTimeout(function run() {
matcher.Woman(name, function(pair) {
console.log(name + ' paired off with ' + pair);
setTimeout(run, random(1000));
});
}, random(1000));
}
function Matcher() {
var self = this;
var men = [];
var women = [];
var process = function() {
while (men.length > 0 && women.length > 0) {
men[0].callback(women[0].name);
women[0].callback(men[0].name);
men.splice(0,1);
women.splice(0,1);
}
}
self.Man = function(name, callback) {
men.push({ name: name, callback: callback });
process();
}
self.Woman = function(name, callback) {
women.push({ name: name, callback: callback });
process();
}
}
var matcher = new Matcher();
for (var i = 0; i < 3; i++) {
Man('Man' + i);
}
for (var i = 0; i < 5; i++) {
Woman('Woman' + i);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment