0

I am working on open-source project. It doesn’t properly meet its specs due to the representation as JavaScript numbers ie let,const... I want to add support for Int, Long Int, and Big Ints similar to c++.

Can anyone please suggest any resource or approach to achieve this?

Thank you

James_sheford
  • 153
  • 2
  • 13

1 Answers1

2

JavaScript has gained BigInt support as a feature a couple of years ago. By now, most users have browsers new enough to support it: https://caniuse.com/bigint.

If you want to support even older browsers, there are a variety of pure JavaScript implementations with different pros and cons, for example JSBI, MikeMcl's bignumber.js, Peter Olson's BigInteger.js, Yaffle's BigInteger. You can study their sources to learn how they're implemented.

For learning about how native BigInt is implemented, this V8 blog post gives some insight.

Side note: JavaScript is perfectly capable of expressing 32-bit integers à la C++ int/int32_t, no BigInts or libraries are required for that. Bitwise binary operations cause JavaScript numbers to behave like 32-bit integers, so you can write (a + b) | 0 to make the addition behave like a C++ int addition.

If all you need is 64-bit integers, it's not difficult to represent them as pairs of 32-bit numbers. There are also several existing libraries that do that (just use your favorite search engine). If you don't actually need arbitrarily big integers, that may be a nice alternative.

jmrk
  • 34,271
  • 7
  • 59
  • 74
  • would like to learn more about it in my particular case. Is there a way of getting in touch with you @jmrk? – James_sheford Mar 07 '22 at 04:07
  • @Karan You can always ask another question. I don't have time to do 1:1 consulting. – jmrk Mar 07 '22 at 13:38
  • Note also that rather than stitching together two 32-bit numbers, javascript 64 bit integers can also be represented directly by [BigUint64Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigUint64Array), stored in platform byte order. BigUint64Array is compatible with all modern browsers... – Trentium Mar 21 '22 at 19:42