3 ms·
var a = [0, 0, 0]; // Accept input from user function modify(i, v) { a[i] = v; // ... } // Trigger an event when two values are eq
by oconnore 11y ago
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) {
// ?
});
}
- brlewis 11y agovar 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');
- oconnore 11y agoNice 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.
- brlewis 11y agoIt eliminates having to think about race conditions. It doesn't automatically mean concise code.