3 ms·
This is an example of why I see node.js having more value in its single-threaded async architecture than in its capacity to use the same programming language on
by brlewis 11y ago
This is an example of why I see node.js having more value in its single-threaded async architecture than in its capacity to use the same programming language on client and server.
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.
- oconnore 11y agovar 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.