UNPKG

1.92 kBJavaScriptView Raw
1'use strict';
2
3Object.defineProperty(exports, '__esModule', { value: true });
4
5/**
6 * > Cyclic rotation for phase-zero windowing
7 *
8 * [![npm install dsp-fftshift](https://nodei.co/npm/dsp-fftshift.png?mini=true)](https://npmjs.org/package/dsp-fftshift/)
9 *
10 * @example
11 * var shift = require('dsp-fftshift')
12 * shift.fftshift(signal)
13 * shift.ifftshift(signal)
14 *
15 * @example
16 * // ES6 syntax
17 * import { fftshift, ifftshift } from 'dsp-fftshift'
18 * fftshift(signal)
19 *
20 * @module fftshift
21 */
22
23/**
24 * Rotate a buffer in place
25 *
26 * from: http://stackoverflow.com/questions/876293/fastest-algorithm-for-circle-shift-n-sized-array-for-m-position
27 *
28 * @param {Array} source - the buffer to rotate
29 * @param {Number} rotations - the number of rotations
30 * @private
31 */
32function rotate (src, n) {
33 var len = src.length;
34 reverse(src, 0, len);
35 reverse(src, 0, n);
36 reverse(src, n, len);
37 return src
38}
39function reverse (src, from, to) {
40 --from;
41 while (++from < --to) {
42 var tmp = src[from];
43 src[from] = src[to];
44 src[to] = tmp;
45 }
46}
47
48/**
49 * Zero-phase windowing alignment
50 *
51 * __CAUTION__: this function mutates the array
52 *
53 * Perform a cyclic shifting (rotation) to set the first sample at the middle
54 * of the buffer (it reorder buffer samples from (0:N-1) to [(N/2:N-1) (0:(N/2-1))])
55 *
56 * Named by the same function in mathlab: `fftshift`
57 *
58 * @param {Array} buffer
59 * @return {Array} the same buffer (with the data rotated)
60 */
61function fftshift (src) {
62 const len = src.length;
63 return rotate(src, Math.floor(len / 2))
64}
65
66/**
67 * Inverse of zero-phase windowing alignment
68 *
69 * __CAUTION__: this function mutates the array
70 *
71 * @see fftshift
72 * @param {Array} buffer
73 * @return {Array} the same buffer (with the data rotated)
74 */
75function ifftshift (src) {
76 const len = src.length;
77 return rotate(src, Math.floor((len + 1) / 2))
78}
79
80exports.fftshift = fftshift;
81exports.ifftshift = ifftshift;