3 ms·
I've mentioned in other comments, but it should be noted that `~~x` or `x | 0` is not same as `Math.floor(x)`. It is rather a shorthand for `Math.trunc(x)` that
by lifthrasiir 3y ago
I've mentioned in other comments, but it should be noted that `~~x` or `x | 0` is not same as `Math.floor(x)`. It is rather a shorthand for `Math.trunc(x)` that is almost correct for x between -2^31 to 2^31 - 1. (Almost, because `Math.trunc(-0.5)` should return -0 while `~~(-0.5)` is +0.) There is also a variant `x >>> 0` which works for x between 0 to 2^32 - 1.
Essentially this trick exploits how JS initially implemented bitwise operations while having no integer-only types. It is safe to use---ECMAScript is unlikely to change bitwise operators in future versions---but only useful for limited cases. Those limited cases, like low-level emulations, happen to be cases where such tricks are very convenient though. As long as you don't naively convert `Math.floor(x)` with `x | 0` or `x >>> 0` I'm fine with them, but this article seems to encourgate that.
- nrabulinski 3y agoI wanted to comment the same thing but then I realized that this post predates Math.trunc by 4 years, hence it makes sense why it’s described in terms of floor and ceil instead :-)
- falcor84 3y agoNice, I don't recall I ever saw `x >>> 0`, bit it reminds me of the infamous "x goes to zero" operator `x --> 0` [0] and its even more expressive sibling, the "x slides to zero" operator [1]. [0] https://stackoverflow.com/q/1642028/493553 https://stackoverflow.com/q/1642028/493553 [1] https://stackoverflow.com/a/8909176/493553 https://stackoverflow.com/a/8909176/493553
- conaclos 3y agoI already used `x >>> 0` to ensure that the integer is a unsigned integer on 32bits. `x|0` ensures that the integer is signed on 32bits.