JSFiddle - React, Tailwind, and code Playground
by kassiomaia
JavaScript
function dft(x) {
return (limit) => {
const N = x.length
const Xk = []
for (var k = 0; k < N; k++) {
let xsum = 0
let ysum = 0
for (var n = 0; n < limit; n++) {
let kth = ((2 * Math.PI) / N) * n * k
xsum += x[n] * Math.cos(kth)
ysum += x[n] * Math.sin(kth)
}
let amplitude = Math.sqrt(Math.pow(xsum, 2) + Math.pow(ysum, 2))
let phase = Math.atan2(ysum, xsum)
Xk.push({
vector: [xsum, ysum],
freq: k,
amplitude,
phase,
rotate: [xsum * Math.cos(phase), ysum * Math.sin(phase)],
})
}
return Xk
}
}
const inputs = [0, 0.707, 1, 0.707, 0, -0.707, -1, -0.07, 2, 3, 4, 6, -50]
const transform = dft(inputs)
console.log(transform(0))