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.
Dependencies: None (standard ES2022 JavaScript). Defines pure JavaScript functions or data; runs cleanly in the sandbox (call console.log in a test harness to inspect values).
const L = ['0001101','0011001','0010011','0111101','0100011',
'0110001','0101111','0111011','0110111','0001011'];
const invert = s => [...s].map(b => b === '0' ? '1' : '0').join('');
const reverse = s => [...s].reverse().join('');
const R = L.map(invert);
const G = R.map(reverse);
const P = ['LLLLLL','LLGLGG','LLGGLG','LLGGGL','LGLLGG','LGGLLG',
'LGGGLL','LGLGLG','LGLGGL','LGGLGL'];
function checkDigit(s) {
if (!/^\d{12}$/.test(s)) throw Error('Enter 12 digits');
let sum = 0;
for (let i = 0; i < 12; i++) {
sum += Number(s[i]) * (i % 2 ? 3 : 1);
}
return String((10 - sum % 10) % 10);
}
function encode(s) {
const n = s + checkDigit(s);
let bits = '101';
for (let i = 1; i <= 6; i++) {
const table = P[Number(n[0])][i-1] === 'L' ? L : G;
bits += table[Number(n[i])];
}
bits += '01010';
for (let i = 7; i < 13; i++) bits += R[Number(n[i])];
return bits + '101';
}
Dependencies: Browser DOM or chapter Interactive Lab environment. Interacts with browser UI elements or dialogs; inspect alongside the chapter Interactive Lab.
Dependencies: None (standard ES2022 JavaScript). Defines pure JavaScript functions or data; runs cleanly in the sandbox (call console.log in a test harness to inspect values).
function decodeForward(b) {
if (!/^[01]{95}$/.test(b) || b.slice(0,3) !== '101' ||
b.slice(45,50) !== '01010' || b.slice(92) !== '101')
return null;
let left = '', right = '', pattern = '';
for (let i = 0; i < 6; i++) {
const group = b.slice(3+7*i,10+7*i);
let d = L.indexOf(group);
if (d >= 0) pattern += 'L';
else { d = G.indexOf(group); pattern += 'G'; }
if (d < 0) return null;
left += d;
d = R.indexOf(b.slice(50+7*i,57+7*i));
if (d < 0) return null;
right += d;
}
const first = P.indexOf(pattern);
if (first < 0) return null;
const n = String(first) + left + right;
return checkDigit(n.slice(0,12)) === n[12] ? n : null;
}
function decode(b) {
return decodeForward(b) || decodeForward(reverse(b));
}
Dependencies: Browser DOM or chapter Interactive Lab environment. Interacts with browser UI elements or dialogs; inspect alongside the chapter Interactive Lab.
Dependencies: None (standard ES2022 JavaScript). Defines pure JavaScript functions or data; runs cleanly in the sandbox (call console.log in a test harness to inspect values).