create butterworth hpf in javascript

To create a Butterworth high-pass filter in JavaScript, we need to follow these steps:

  1. Define the filter parameters: cutoff frequency and filter order
  2. Calculate the filter coefficients using the Butterworth filter design equation
  3. Implement the filter function using the filter coefficients and the recursive formula

Here is the code that implements a Butterworth high-pass filter:

index.tsx
// Define the filter parameters
const cutoffFreq = 1000; // Hz
const order = 4;

// Calculate the filter coefficients
const wc = 2 * Math.PI * cutoffFreq;
const T = 1 / sampleRate; // sample rate is assumed to be defined
const alpha = Math.sin(wc * T / (2 * order)) / Math.cos(wc * T / (2 * order));
const a = new Array(order + 1).fill(0);
const b = new Array(order + 1).fill(0);
for (let k = 0; k < order / 2; k++) {
  const theta = Math.PI / 2 + k * Math.PI / order;
  const s = alpha * Math.sin(theta);
  const c = alpha * Math.cos(theta);
  const alpha2 = 2 * Math.sqrt(2) * s * c;
  const beta = Math.pow(s, 2) - Math.pow(c, 2);
  a[k] = alpha2 + beta;
  a[order - k] = alpha2 - beta;
  b[k] = Math.pow(2, order - 1) * (Math.pow(alpha, 2) + Math.pow(s, 2) - Math.pow(c, 2));
  b[order - k] = -b[k];
}
if (order % 2 == 1) {
  const alpha2 = 2 * alpha;
  a[Math.floor(order / 2)] = Math.pow(alpha, 2);
  b[Math.floor(order / 2)] = Math.pow(alpha, order);
}

// Implement the filter function
function butterworthHPF(input) {
  let output = 0;
  for (let k = 0; k <= order; k++) {
    output += b[k] * input[k] - a[k] * output[k];
  }
  return output;
}
1155 chars
36 lines

Note that this implementation assumes the input signal is a one-dimensional array of samples, and the output signal is a one-dimensional array of filtered samples. Also, the sample rate needs to be defined before using the filter.

gistlibby LogSnag