var a = [0, 0, 0];
// Accept input from user
function modify(i, v) {
a[i] = v;
// ...
}
// Trigger an event when two values are equal
function waitUntil(i, j) {
return new Promise(function(res, rej) {
// ?
});
} var EventEmitter = require('events').EventEmitter;
var Promise = require('promise');
function Answer() {
var values = [];
var emitters = [];
this.modify = function(index, value) {
values[index] = value;
if (emitters[index]) {
emitters[index].emit('modified');
}
};
this.waitUntilEqual = function(index1, index2) {
return new Promise(function(resolve) {
if (!emitters[index1]) {
emitters[index1] = new EventEmitter();
}
if (!emitters[index2]) {
emitters[index2] = new EventEmitter();
}
function compare() {
if (values[index1] === values[index2]) {
resolve();
}
}
emitters[index1].on('modified', compare);
emitters[index2].on('modified', compare);
});
};
}
var check = new Answer();
check.waitUntilEqual(0, 1).then(function () { console.log('equal'); });
check.modify(0, 'x');
check.modify(1, 'x');Nice job! But I thought you said this problem would be eliminated by the architecture of Node.js? This appears to be longer and more complex than the fully parallel and concurrent Haskell solution.
More generally, when you discover a tricky problem that would make a good interview question, oftentimes there's an architectural decision that would eliminate the problem.