Chapter 08 of 22 Part II: Networks and Communication

The Incredible Journey of an Internet Packet

3 Verified Book Snippets

Every .js file below is byte-identical (SHA-256 verified) to the printed code in Volume 1. Runnable blocks execute inside an isolated sandboxed iframe and Web Worker with a 2-second timeout and zero network access.

Download Chapter ZIP

Resolve (Ch. 08 Example 1)

File: block-01.js (byte-identical) · 276 bytes · SHA-256: 019c4cf82d17…
DNS Standalone runnable

Dependencies: None (standard ES2022 JavaScript). Runs directly in Node.js or the isolated Web Worker sandbox and prints console output.

const directory = new Map([
  ["lab.example", "192.0.2.10"],
  ["library.example", "198.51.100.20"]
]);
function resolve(name) {
  return directory.get(name.toLowerCase())
    ?? "Name not found";
}
console.log(resolve("lab.example"));
console.log(resolve("missing.example"));
Download .js

Route (Ch. 08 Example 2)

File: block-02.js (byte-identical) · 774 bytes · SHA-256: dd0281042d96…
DNS Standalone runnable

Dependencies: None (standard ES2022 JavaScript). Runs directly in Node.js or the isolated Web Worker sandbox and prints console output.

function route(edges, start, end) {
  const dist = {[start]: 0}, paths = {[start]: [start]};
  const nodes = new Set(edges.flatMap(e => e.slice(0,2)));
  while (nodes.size) {
    const u = [...nodes].sort((a,b) =>
      (dist[a] ?? Infinity) - (dist[b] ?? Infinity))[0];
    if (dist[u] === undefined) break;
    nodes.delete(u);
    if (u === end) return {cost:dist[u], path:paths[u]};
    for (const [a,b,w] of edges) {
      const v = a === u ? b : b === u ? a : null;
      if (v !== null && nodes.has(v) &&
          dist[u]+w < (dist[v] ?? Infinity)) {
        dist[v] = dist[u]+w;
        paths[v] = [...paths[u],v];
      }
    }
  }
  return null;
}
const links = [["A","B",2],["B","D",2],
               ["A","C",3],["C","D",4]];
console.log(route(links,"A","D"));
Download .js

Rebuild (Ch. 08 Example 3)

File: block-03.js (byte-identical) · 614 bytes · SHA-256: 0179adb980b7…
DNS Standalone runnable

Dependencies: None (standard ES2022 JavaScript). Runs directly in Node.js or the isolated Web Worker sandbox and prints console output.

function rebuild(parts, total) {
  const byIndex = new Map();
  for (const {seq, data} of parts) {
    if (Number.isInteger(seq) && seq >= 0 && seq < total)
      byIndex.set(seq, data);
  }
  const missing = [];
  for (let i=0; i<total; i++) {
    if (!byIndex.has(i)) missing.push(i);
  }
  if (missing.length) return {missing};
  return {message: Array.from({length:total},
    (_,i) => byIndex.get(i)).join("")};
}
const parts = [{seq:2,data:"!"},
               {seq:0,data:"Hello "}];
console.log(rebuild(parts,3)); // missing: [1]
parts.push({seq:1,data:"Leo"});
console.log(rebuild(parts,3)); // Hello Leo!
Download .js