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

BigInt examples #247

Open
Rudxain opened this issue Apr 26, 2022 · 0 comments
Open

BigInt examples #247

Rudxain opened this issue Apr 26, 2022 · 0 comments
Labels
new-example A proposal of the new example

Comments

@Rudxain
Copy link

Rudxain commented Apr 26, 2022

Conditionally-typed zero

const zeros = ([undefined, null, true, 5, 5n, 'txt', {}, []]).map(x => x ^ x)
console.log(zeros.every(z => z === 0)) // "false"

Explanation: The caret ^ is the XOR operator, XOR-ing a value with itself always returns zero, even in JS. But applying XOR to a BigInt (5n in this case) returns a zero of type BigInt.

typeof 0 == 'number' // true
typeof 0n == 'bigint' // true

So even though BigInt is a numeric-like value, it's not a Number.
The self-XOR is a shorthand for this:

typeof x?.valueOf() == 'bigint' ? 0n : 0

Except for the fact that Symbols will cause ^ to throw.

map replaces each element of an iterable (not in-place), every tests a predicate.

BigInt method that only works with Numbers

BigInt.asIntN(8, 257n) // 1n
BigInt.asIntN(8n, 257n) // throws an error

Explanation: The 1st parameter of that static method only accepts Number-typed arguments, more specifically, integer Numbers. That's because it specifies the exponent of the modulo divisor, which is expected to be small.

Links

More pitfalls/footguns/gotchas here: https://github.com/tc39/proposal-bigint#gotchas--exceptions
Spec here: https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-bigint-objects
Docs here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt

@Rudxain Rudxain added the new-example A proposal of the new example label Apr 26, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
new-example A proposal of the new example
Projects
None yet
Development

No branches or pull requests

1 participant