Reverse the lowest width bits of an integer for FFT ordering
An audio visualizer runs a Fast Fourier Transform on every frame. Before the transform, it reorders the samples so that the sample at index i moves to the index whose binary digits are those of i written backwards, using a fixed number of bits. With 3 bits, index 1 (001) moves to index 4 (100).
Implement reverseBits(n, width). It reverses the order of the lowest width bits of n and returns the result.
reverseBits(n, width?) // => number
width is the number of bits to reverse. It defaults to 32 and must be an integer from 1 to 32. Otherwise, throw a RangeError.n must be an integer from 0 to 2width - 1, so that it fits in width bits. Otherwise, throw a RangeError.8, 1 is 00000001, and its reverse is 10000000 (128).32, reverseBits(1) is 2147483648, not -2147483648.toString(2)).reverseBits(6, 3); // 110 => 011 => 3
reverseBits(11, 4); // 1011 => 1101 => 13
reverseBits(13, 8); // 00001101 => 10110000 => 176
reverseBits(1); // width 32 => 2147483648
[0, 1, 2, 3, 4, 5, 6, 7].map((i) => reverseBits(i, 3));
// => [0, 4, 2, 6, 1, 5, 3, 7]
reverseBits(8, 3); // throws RangeError: 8 needs 4 bits