1loc icon indicating copy to clipboard operation
1loc copied to clipboard

Add disclaimer to isPowerOfTwo

Open daprahamian opened this issue 4 years ago • 0 comments

Saw this repo b/c it was in js weekly newsletter. B/c of the way bitwise AND work on numbers in JS (casting down to 32-bit signed integers), the isPowerOfTwo function will return a lot of false positives:

// Any non-integer `< 2 ** 32` will be floored.
// Below, the bitwise operation turns 1.5 into 1.
isPowerOfTwo(1.5); // true

// Only the least-significant 32 bits are saved in bitwise ops.
// Below, the bitwise operation turns number into 1.
isPowerOfTwo(2 ** 40 + 1); // true

though afaik it should work with it's BigInt variant:

const isPowerOfTwo = number => (number & (number - 1n)) === 0n;

isPowerOfTwo(2n ** 40n + 1n); // false 

Maybe add a disclaimer to the function specifying that it only works on positive integers <= 2 ** 32?

daprahamian avatar May 08 '20 21:05 daprahamian