Skip to content

Instantly share code, notes, and snippets.

@CedricSch
Last active May 30, 2021
Embed
What would you like to do?
Solution for exercise 7.3 A tamper-free queue
import http from "http";
/*------------------------------------------------------------------------------------------------------------*/
class Queue {
constructor(executor) {
const queue = [];
let resolverFunctions = [];
async function enqueue(element) {
if(resolverFunctions.length) {
const resolve = resolverFunctions.shift();
resolve(element);
} else {
queue.push(element);
}
return queue.length;
}
Queue.prototype.dequeue = async function() {
if(!queue.length) {
console.log("Queue is empty. Waiting for new element.")
return new Promise( (resolve) => {
resolverFunctions.push(resolve);
});
}
return Promise.resolve(queue.shift());
}
executor({enqueue});
}
}
/*------------------------------------------------------------------------------------------------------------*/
const queue = new Queue( ({ enqueue }) => {
const server = http.createServer( (request, response) => {
let body = "";
request.setEncoding("utf-8");
request.on("data", (chunk) => {
body += chunk;
});
request.on("end", () => {
const words = body.split(" ").map( word => word.toUpperCase());
for(const word of words) {
enqueue(word);
}
body = "";
response.writeHead(200, { "Content-Type" : "text/plain" })
response.end("OK");
})
});
server.listen(8080, () => {
console.log("Server started on port %i", 8080);
});
});
/*------------------------------------------------------------------------------------------------------------*/
async function printWordsAsync(queue) {
while(1) {
const word = await queue.dequeue();
console.log("Uppercase word: %s", word);
}
}
// Kickoff function
printWordsAsync(queue);
/*------------------------------------------------------------------------------------------------------------*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment