Last active
June 26, 2023 17:08
-
-
Save CedricSch/f822e7b235e548637e570c88fd6471d2 to your computer and use it in GitHub Desktop.
Solution for exercise 7.3 A tamper-free queue
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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