Means to an End done!

This commit is contained in:
Daniel Flanagan 2022-09-26 23:53:34 -05:00
parent 1c7efe5a9e
commit de9e412451

52
main.ts
View file

@ -1,5 +1,4 @@
import { copy } from "https://deno.land/std@0.157.0/streams/conversion.ts?s=copy"; import { BufReader } from "https://deno.land/std@0.157.0/io/buffer.ts";
import { Buffer } from "https://deno.land/std@0.157.0/io/buffer.ts";
import { ByteSet } from "https://deno.land/x/bytes@1.0.3/mod.ts"; import { ByteSet } from "https://deno.land/x/bytes@1.0.3/mod.ts";
const QUERY_SIZE = 9; const QUERY_SIZE = 9;
@ -22,29 +21,54 @@ for await (const conn of listener) {
// problem 2 // problem 2
async function meansToAnEnd(conn: Deno.Conn) { async function meansToAnEnd(conn: Deno.Conn) {
try { try {
const prices = [];
for await (const query of queries(conn)) { for await (const query of queries(conn)) {
console.log("Query:", query); if (query == null) break;
conn.write(ByteSet.from(Uint8Array.from([0]), "big").buffer); const bs = ByteSet.from(query, "big");
const queryChar = String.fromCharCode(bs.read.uint8());
const a1 = bs.read.int32();
const a2 = bs.read.int32();
if (queryChar == "I") {
console.log(conn.remoteAddr, "Pushing I:", [a1, a2]);
prices.push([a1, a2]);
} else if (queryChar == "Q") {
console.log(conn.remoteAddr, "Querying:", a1, a2);
let numMatches = 0;
let sum = 0;
for (const [ts, price] of prices) {
if (ts < a1 || ts > a2) continue;
numMatches++;
sum += price;
}
let result = Math.floor(sum / numMatches);
if (isNaN(result)) result = 0;
console.log(
conn.remoteAddr,
`Result for ${prices.length} prices: ${sum} / ${numMatches} = ${result}`,
);
const response = new ByteSet(4, "big");
response.write.int32(result);
conn.write(response.buffer);
}
} }
console.log("Done!"); console.log("Done!");
} catch (err) { } catch (err) {
console.error(err); console.error("Error processing query:", err);
} }
} }
function queries(conn: Deno.Conn) { function queries(conn: Deno.Conn) {
return { return {
async *[Symbol.asyncIterator]() { async *[Symbol.asyncIterator]() {
const b = new Uint8Array(1024); const b = new Uint8Array(9);
const q = new Uint8Array(); const reader = new BufReader(conn, QUERY_SIZE);
let bytesRead = 0; try {
console.debug(b.length); while (await reader.readFull(b) != null) {
while (bytesRead < QUERY_SIZE) { yield b;
const n = await conn.read(b); }
bytesRead += n; } catch (err) {
console.debug(n, b.length); console.error("Error receiving query:", err);
} }
yield q;
}, },
}; };
} }