peterolson / BigInteger.js

An arbitrary length integer library for Javascript
The Unlicense
1.12k stars 187 forks source link

No documentation about asIntN() and asUintN() methods #167

Open ppKrauss opened 5 years ago

ppKrauss commented 5 years ago

Hi, there are some documentation about how BigInteger wraps the signal of a number?

As (2018) "BigInt is being added as a native feature of JavaScript. This library now works as a polyfill", is important to check how is orking about it.

See https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/BigInt#Methods

Yaffle commented 5 years ago

Probably, could be implemented as:

bigInt.asUintN = function (bits, bigint) {
  bigint = bigInt(bigint);
  if (typeof bigint.value === "bigint") {
    return bigInt(BigInt.asUintN(bits, bigint.value));
  }
  const p2bits = bigInt(1).shiftLeft(bits);
  const mod = bigint.and(p2bits.subtract(1));
  return mod;
};
bigInt.asIntN = function (bits, bigint) {
  bigint = bigInt(bigint);
  if (typeof bigint.value === "bigint") {
    return bigInt(BigInt.asIntN(bits, bigint.value));
  }
  const p2bits = bigInt(1).shiftLeft(bits);
  const mod = bigint.and(p2bits.subtract(1));
  return mod.greaterOrEquals(p2bits.subtract(mod)) ? mod.subtract(p2bits) : mod;
};

If needed.

peterolson commented 5 years ago

If someone wants to add a pull request for this feature I'll merge it in.