Chapter 02 of 22 Part I: Foundations of Digital Information

The Secret Mathematics of Everyday Numbers

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

block-01.js

Printed book snippet (byte-identical) · 444 bytes · SHA-256: cd24051198c1…
Standalone runnable

Dependencies: None (standard ES2022 JavaScript). Runs directly in Node.js or the isolated browser sandbox and logs output.

function passesLuhn(text) {
  if (!/^\d+$/.test(text)) return false;
  let sum = 0;
  let doubleNext = false;
  for (let i = text.length - 1; i >= 0; i--) {
    let digit = Number(text[i]);
    if (doubleNext) {
      digit *= 2;
      if (digit > 9) digit -= 9;
    }
    sum += digit;
    doubleNext = !doubleNext;
  }
  return sum % 10 === 0;
}
console.log(passesLuhn("79927398713")); // true
console.log(passesLuhn("79927398714")); // false
Download .js

block-02.js

Printed book snippet (byte-identical) · 600 bytes · SHA-256: 4489fada3951…
Standalone runnable

Dependencies: None (standard ES2022 JavaScript). Runs directly in Node.js or the isolated browser sandbox and logs output.

function weightedSum(text, weights) {
  let sum = 0;
  for (let i = 0; i < text.length; i++) {
    sum += Number(text[i]) * weights[i % weights.length];
  }
  return sum;
}
function mod10Check(text) {
  if (!/^\d+$/.test(text)) return null;
  let sum = weightedSum(text, [1, 3]);
  return (10 - sum % 10) % 10;
}
function isbn13Passes(text) {
  if (!/^97[89]\d{10}$/.test(text)) return false;
  return mod10Check(text.slice(0, 12)) === Number(text[12]);
}
console.log(isbn13Passes("9780306406157")); // true
console.log(isbn13Passes("9780306406158")); // false
console.log(mod10Check("314159")); // 5
Download .js

block-03.js

Printed book snippet (byte-identical) · 551 bytes · SHA-256: 9ba656365217…
Standalone runnable

Dependencies: None (standard ES2022 JavaScript). Runs directly in Node.js or the isolated browser sandbox and logs output.

function labLabel(payload) {
  if (!/^\d{6}$/.test(payload)) return null;
  let sum = 0;
  for (let i = 0; i < 6; i++) {
    let weight = i % 2 === 0 ? 1 : 3;
    sum += Number(payload[i]) * weight;
  }
  let check = (10 - sum % 10) % 10;
  return "LAB-" + payload + check;
}
function labelPasses(label) {
  if (!/^LAB-\d{7}$/.test(label)) return false;
  return labLabel(label.slice(4, 10)) === label;
}
console.log(labLabel("314159")); // LAB-3141595
console.log(labelPasses("LAB-3141595")); // true
console.log(labelPasses("LAB-3141596")); // false
Download .js