phuocng / 1loc

What's your favorite JavaScript single LOC (line of code)?

Home Page:https://phuoc.ng/collection/1-loc

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Add disclaimer to isPowerOfTwo

daprahamian opened this issue · 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?