4.3.0 • Published 2 years ago

jsbi v4.3.0

Weekly downloads
331,122
License
Apache-2.0
Repository
github
Last release
2 years ago

JSBI — pure-JavaScript BigInts Build status jsbi on npm

JSBI is a pure-JavaScript implementation of the ECMAScript BigInt proposal, which officially became a part of the JavaScript language in ES2020.

Installation

npm install jsbi --save

Usage

import JSBI from './jsbi.mjs';

const max = JSBI.BigInt(Number.MAX_SAFE_INTEGER);
console.log(String(max));
// → '9007199254740991'
const other = JSBI.BigInt('2');
const result = JSBI.add(max, other);
console.log(String(result));
// → '9007199254740993'

Note: explicitly call toString on any JSBI instances when console.log()ing them to see their numeric representation (e.g. String(max) or max.toString()). Without it (e.g. console.log(max)), you’ll instead see the object that represents the value.

Use babel-plugin-transform-jsbi-to-bigint to transpile JSBI code into native BigInt code.

Refer to the detailed instructions below for more information.

Why?

Native BigInts are already shipping in modern browsers (at the time of this writing, Google Chrome 67+, Opera 54+, Firefox 68+, Edge 79+, Safari 14+) and Node.js (v10.4+), but some users are still running older browsers — which means you can't use them yet if you want your code to run everywhere.

To use BigInts in code that you want to run everywhere, you need a library. But there’s a difficulty: the BigInt proposal changes the behavior of operators (like +, >=, etc.) to work on BigInts. These changes are impossible to polyfill directly; and they are also making it infeasible (in most cases) to transpile BigInt code to fallback code using Babel or similar tools. The reason is that such a transpilation would have to replace every single operator in the program with a call to some function that performs type checks on its inputs, which would incur an unacceptable performance penalty.

The solution is to do it the other way round: write code using a library’s syntax, and transpile it to native BigInt code when available. JSBI is designed for exactly this purpose: it provides a BigInt “polyfill” implementation that behaves exactly like the upcoming native BigInts, but with a syntax that you can ship on all browsers, today.

Its advantages over other, existing big-integer libraries are:

  • it behaves exactly like native BigInts do where they are available, so to eventually migrate to those, you can mechanically update your code’s syntax; no re-thinking of its logic will be required.
  • strong focus on performance. On average, JSBI is performance-competitive with the native implementation that Google Chrome is currently shipping. (Note: we expect this statement to gradually become outdated as browsers invest in additional optimizations.)

How?

Except for mechanical differences in syntax, you use JSBI-BigInts just like you would use native BigInts. Some things even look the same, after you replace BigInt with JSBI.BigInt:

Operationnative BigIntsJSBI
Creation from Stringa = BigInt('456')a = JSBI.BigInt('456')
Creation from Numbera = BigInt(789)a = JSBI.BigInt(789)
Conversion to Stringa.toString(radix)a.toString(radix)
Conversion to NumberNumber(a)JSBI.toNumber(a)
TruncationBigInt.asIntN(64, a)JSBI.asIntN(64, a)
BigInt.asUintN(64, a)JSBI.asUintN(64, a)
Type checktypeof a === 'bigint'a instanceof JSBI

Most operators are replaced by static functions:

Operationnative BigIntsJSBI
Additionc = a + bc = JSBI.add(a, b)
Subtractionc = a - bc = JSBI.subtract(a, b)
Multiplicationc = a * bc = JSBI.multiply(a, b)
Divisionc = a / bc = JSBI.divide(a, b)
Remainderc = a % bc = JSBI.remainder(a, b)
Exponentiationc = a ** bc = JSBI.exponentiate(a, b)
Negationb = -ab = JSBI.unaryMinus(a)
Bitwise negationb = ~ab = JSBI.bitwiseNot(a)
Left shiftingc = a << bc = JSBI.leftShift(a, b)
Right shiftingc = a >> bc = JSBI.signedRightShift(a, b)
Bitwise “and”c = a & bc = JSBI.bitwiseAnd(a, b)
Bitwise “or”c = a \| bc = JSBI.bitwiseOr(a, b)
Bitwise “xor”c = a ^ bc = JSBI.bitwiseXor(a, b)
Comparison to other BigIntsa === bJSBI.equal(a, b)
a !== bJSBI.notEqual(a, b)
a < bJSBI.lessThan(a, b)
a <= bJSBI.lessThanOrEqual(a, b)
a > bJSBI.greaterThan(a, b)
a >= bJSBI.greaterThanOrEqual(a, b)

The functions above operate only on BigInts. (They don’t perform type checks in the current implementation, because such checks are a waste of time when we assume that you know what you’re doing. Don’t try to call them with other inputs, or you’ll get “interesting” failures!)

Some operations are particularly interesting when you give them inputs of mixed types, e.g. comparing a BigInt to a Number, or concatenating a string with a BigInt. They are implemented as static functions named after the respective native operators:

Operationnative BigIntsJSBI
Abstract equality comparisonx == yJSBI.EQ(x, y)
Generic “not equal”x != yJSBI.NE(x, y)
Generic “less than”x < yJSBI.LT(x, y)
Generic “less than or equal”x <= yJSBI.LE(x, y)
Generic “greater than”x > yJSBI.GT(x, y)
Generic “greater than or equal”x >= yJSBI.GE(x, y)
Generic additionx + yJSBI.ADD(x, y)

The variable names x and y here indicate that the variables can refer to anything, for example: JSBI.GT(101.5, BigInt('100')) or str = JSBI.ADD('result: ', BigInt('0x2A')).

Unfortunately, there are also a few things that are not supported at all:

Unsupported operationnative BigIntsJSBI
literalsa = 123n;N/A ☹
incrementa++N/A ☹
a + 1nJSBI.add(a, JSBI.BigInt('1'))
decrementa--N/A ☹
a - 1nJSBI.subtract(a, JSBI.BigInt('1'))

It is impossible to replicate the exact behavior of the native ++ and -- operators in a polyfill/library. Since JSBI is intended to be transpiled away eventually, it doesn’t provide a similar-but-different alternative. You can use JSBI.add() and JSBI.subtract() instead.

Since version 4.2.0, polyfills for DataView operations are included (where dv is a DataView, i is an index, le is an optional boolean indicating little endian mode, and x is a BigInt or a JSBI instance, respectively):

native BigInts/DataViewsJSBI
dv.getBigInt64(i, le)JSBI.DataViewGetBigInt64(dv, i, le)
dv.setBigInt64(i, x, le)JSBI.DataViewSetBigInt64(dv, i, x, le)
dv.getBigUint64(i, le)JSBI.DataViewGetBigUint64(dv, i, le)
dv.setBigUint64(i, x, le)JSBI.DataViewSetBigUint64(dv, i, x, le)

When?

Now! The JSBI library is ready for use today.

Once BigInts are natively supported everywhere, use babel-plugin-transform-jsbi-to-bigint to transpile your JSBI code into native BigInt code once and for all.

View our issue tracker to learn more about out our future plans for JSBI, and please join the discussion!

A more vague future plan is to use the JSBI library (or an extension to it) as a staging ground for additional BigInt-related functionality. The official proposal is intentionally somewhat minimal, and leaves further “library functions” for follow-up proposals. Examples are a combined exp+mod function, and bit manipulation functions.

Development

  1. Clone this repository and cd into the local directory.

  2. Use the Node.js version specified in .nvmrc:

    nvm use
  3. Install development dependencies:

    npm install
  4. Run the tests:

    npm test

    See npm run for the list of commands.

For maintainers

How to publish a new release

  1. On the main branch, bump the version number in package.json:

    npm version patch -m 'Release v%s'

    Instead of patch, use minor or major as needed.

    Note that this produces a Git commit + tag.

  2. Push the release commit and tag:

    git push && git push --tags

    Our CI then automatically publishes the new release to npm.

confidence-sdkconfidence-sdk-v13@conedex/conedex-sdk-core@benboba790111/uniswap-v2-sdk@trebodex/sdk@trebodex/trebodex-sdk-core@nekomeowww/uniscam-sdk@nekomeowww/uniswap-earndefi-sdk@muhammadwajidshahid/swap-sdk@react-w3/use-wallet@exchange-one/sdk@exchange-one/sdk-core@harmony-swoop/sdk@arthswap/widgets@azure/cosmos@linbingdefi/sdk@openos.com/uniswaptttswap-sdk@magic-finance-cards/magic-sdk@roc-protocol/roc-sdk@makkii-dev/aion-web3-avm-abi@kidsagree/uimy-deerfi-sdkenigma-p2p@crisog/uniswap-sdk@batsoft/swappornswap-sdk@narwhalosaurus/ui@pornswap/pornswap-sdkheco-sdk@twswap/sdkcustomsdkttcryptoswap-sdk-corecasperlabs-sdk@thismr/bitmindtest-sdk1@aliumswap/sdkboa-crypto-tsgreenteaswap-libs-sdk@thecompounder/sdk@theanthill/pancakeswap-libs-sdk@shibance/sdk@saberhq/sdkdepth-swap@freeswap/sdk@yuetlooo/ui@zetaswap/sdk@zettaswap/sdk@sonicswap/sdk-devdungnv-sdkztopiauniswaptest@bscsswap/sdk@beswap/sdkcortex-test-sdkfreeswap-sdkfreeswap-sdk2@manekiswap/manekiswap-sdkliger-sdkinmergerswap-sdkokexshibaswap-sdksphinxsjc-sdkbimswap-sdkhayek-uniswap-sdk@avacadodefi/sdkv1qdexswapsdkcronswap-sdkalpes-sdk@dahuswap/sdksample-sdkapeswap-sdk@wanwantip/jdi-sdk@dexorzo/sdk@heshiswap/sdk-coremathswap-sdkinmerger-ropsten-sdk@ashalfarhan/legionswap-sdk-testnet@duythao_bacoor/sdk@oboswap/bnbsdk@oboswap/ethsdk@trader-b0b/sdk@ladarken/sdk@ladarken/sdktestpawsswap-sdkpolygon-moonwalkerswap-sdkhuobiswapsdkrcpswaptestgolswap-sdk@qdexgo/bscsdk@qdexgo/ethsdk@qdexgo/matic-sdk@jjf7/gol-sdk@alayaswap/sdk-core@circusdao/clownswap-v2-sdk@circusdao/juggler-v2-sdk@cherryswap/sdk@fathomswap/sdkdotoracle-sdk@intercroneswap/sdk-core@kdefi/sdk@steban1/bchswap-sdk@koingfu.com/rskswap-sdk
4.3.0

2 years ago

4.2.1

2 years ago

4.2.0

2 years ago

4.1.0

2 years ago

4.0.0

2 years ago

3.2.5

2 years ago

3.2.4

3 years ago

3.2.2

3 years ago

3.2.3

3 years ago

3.2.1

3 years ago

3.2.0

3 years ago

3.1.6

3 years ago

3.1.5

3 years ago

3.1.4

4 years ago

3.1.3

4 years ago

3.1.2

4 years ago

3.1.1

5 years ago

3.1.0

5 years ago

3.0.1

5 years ago

3.0.0

5 years ago

2.0.5

5 years ago

2.0.4

5 years ago

2.0.3

5 years ago

2.0.2

5 years ago

2.0.1

5 years ago

2.0.0

5 years ago

1.0.0

5 years ago

0.0.0

6 years ago