[JS]BigIntでMathが使えない件

[JS]BigIntでMathが使えない件

2022-06-1211 min read

目次

  1. はじめに
  2. 1-math-オブジェクトっぽいものを自前で実装する
  3. 2-プロトタイプメソッドを追加してみる

はじめに

JS の BigIntMath を利用することはできません。

Math は Number 型のみ利用できます。

例えば以下のコードの場合、引数が BigInt のため実行に失敗します。

console.log(Math.abs(-1)); // 1
console.log(Math.abs(-1n)); // TypeError: Cannot convert a BigInt value to a number

それでも、abs とか max, min が利用できたらなと思っていたので、対策を考えてみました。

1. Math オブジェクトっぽいものを自前で実装する

Math オブジェクトっぽいものを自前で実装してみました。

BigInt では浮動小数点数は扱えないので、PI や 三角関数は除外しました。

const BigMath = {
  abs(x) {
    if (x < 0n) {
      return -1n * x;
    }
    return x;
  },
  min(base, ...values) {
    for (const value of values) {
      if (value < base) {
        base = value;
      }
    }
    return base;
  },
  max(base, ...values) {
    for (const value of values) {
      if (value > base) {
        base = value;
      }
    }
    return base;
  },
  pow(base, ex) {
    return base ** ex;
  },
  sign(x) {
    if (x === 0n) {
      return 0n;
    }
    return x < 0n ? -1n : 1n;
  },
};

実行例

console.log(BigMath.max(1n, 2n, 3n)); // 3n

2. プロトタイプメソッドを追加してみる

イケてる実装ではないですが、プロトタイプメソッドを使う方法も思いつきました。

BigInt.prototype.abs = function() {
  return -this;
};
BigInt.prototype.pow = function(ex) {
  return this ** ex;
};
BigInt.prototype.min = function(...values) {
  const base = this;
  for (const value of values) {
    if (value < base) {
      base = value;
    }
  }
  return base;
};
BigInt.prototype.max = function(...values) {
  const base = this;
  for (const value of values) {
    if (value > base) {
      base = value;
    }
  }
  return base;
};

実行例

let x = BigInt(-2);
console.log(x.abs()); // 2n
console.log(x.pow(2n)); // 4n
console.log(x.max(-3n, -4n)); // -2n
Author
githubzennqiita
ただの備忘録です。

※外部送信に関する公表事項