Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add disclaimer to isPowerOfTwo #162

Open
daprahamian opened this issue May 8, 2020 · 0 comments
Open

Add disclaimer to isPowerOfTwo #162

daprahamian opened this issue May 8, 2020 · 0 comments

Comments

@daprahamian
Copy link

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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant