diff options
author | Holden Rohrer <holden.rohrer@gmail.com> | 2019-12-24 20:55:52 -0500 |
---|---|---|
committer | Holden Rohrer <holden.rohrer@gmail.com> | 2019-12-27 14:52:44 -0500 |
commit | 4bd0a90631cc07d1433a11079bfc2d54d51fb644 (patch) | |
tree | 976b19921de5af07170716104785948cdbf2978d | |
parent | 2ca99ea944868a7c0a90ebfa9b6eb8669ca81732 (diff) |
added queue.js to simplify jarvis
-rw-r--r-- | examples/jarvis.js | 16 | ||||
-rw-r--r-- | tools/queue.js | 24 |
2 files changed, 27 insertions, 13 deletions
diff --git a/examples/jarvis.js b/examples/jarvis.js index d60bc44..00b4610 100644 --- a/examples/jarvis.js +++ b/examples/jarvis.js @@ -5,6 +5,7 @@ const Socket = require('../socket'); const getdims = require('../utils/getdims'); const tilekeys = require('../utils/tilekeys'); const Search = require('../tools/search'); +const Queue = require('../tools/queue'); var main = new Socket(); @@ -57,21 +58,10 @@ function identity(sender){ let response = new Space(); response.adhoc('yes, my liege'); -let queue = []; // Must be expanded to handle actual use cases -let open = true; -function dequeue(){ - if (queue.length == 0) - open = true; - else{ - open = false; - main.write(queue.shift()) // Make more general (possibly a function pointer or a conf variable) - setTimeout(dequeue, 1000); - } -} +let writes = new Queue(1000, 200, (elems) => main.write(elems)); function respond(coord){ console.log('called at', coord); response.loc = coord; - queue.push(response.towrite()); - if (open) dequeue(); + writes.enqueue(...response.towrite()); } diff --git a/tools/queue.js b/tools/queue.js new file mode 100644 index 0000000..ebe17cd --- /dev/null +++ b/tools/queue.js @@ -0,0 +1,24 @@ +// A generalized queue object for rapid responses (doesn't do prioritization or algorithmic timesharing) + +module.exports = function(delayms, maxExport, call){ + let queue = []; + let open = true; + let getObjs = (maxExport == 1) ? + () => queue.shift() : + () => queue.splice(0, maxExport) ; + this.enqueue = function(){ + for (let i = 0; i < arguments.length; i++) + queue.push(arguments[i]); + if (open) dequeue(); + } + + function dequeue(){ + if (queue.length == 0) + open = true; + else { + open = false; + call(getObjs()); + setTimeout(dequeue, delayms); + } + } +} |