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).
function tone(f, fs, n, amplitude = 1) {
return Array.from({length:n}, (_,i) =>
amplitude * Math.sin(2*Math.PI*f*i/fs));
}
function spectrum(x, fs) {
const n = x.length, result = [];
for (let k=0; k<=Math.floor(n/2); k++) {
let re=0, im=0;
for (let i=0; i<n; i++) {
const a=2*Math.PI*k*i/n;
re += x[i]*Math.cos(a);
im -= x[i]*Math.sin(a);
}
result.push({hz:k*fs/n,
strength:Math.hypot(re,im)/n});
}
return result;
}
function dominant(x, fs) {
return spectrum(x,fs).slice(1)
.reduce((a,b)=>a.strength>=b.strength?a:b).hz;
}
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).
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 cancel(noise, gain=1, phase=0) {
return noise.map((v,i)=>v+gain*Math.sin(i*2*Math.PI/32+phase));
}
function rms(x) {
return Math.sqrt(x.reduce((s,v)=>s+v*v,0)/x.length);
}