// -----------------------------
// BigInt / Number 安全演算ユーティリティ
// -----------------------------
// 安全変換関数
function toSafeType(a, b) {
const isBigIntA = typeof a === "bigint";
const isBigIntB = typeof b === "bigint";
// 両方 BigInt
if (isBigIntA && isBigIntB) return [a, b];
// どちらか小数なら Number 優先
if (!Number.isInteger(a) || !Number.isInteger(b)) {
return [Number(a), Number(b)];
}
// どちらか BigInt → 両方 BigInt に統一
if (isBigIntA || isBigIntB) {
return [BigInt(a), BigInt(b)];
}
// それ以外(両方 Number)
return [a, b];
}
// 安全演算ラッパー
const SafeMath = {
add(a, b) {
const [x, y] = toSafeType(a, b);
return typeof x === "bigint" ? x + y : x + y;
},
sub(a, b) {
const [x, y] = toSafeType(a, b);
return typeof x === "bigint" ? x - y : x - y;
},
mul(a, b) {
const [x, y] = toSafeType(a, b);
return typeof x === "bigint" ? x * y : x * y;
},
div(a, b) {
const [x, y] = toSafeType(a, b);
if (typeof x === "bigint") {
if (y === 0n) throw new Error("Division by zero");
return x / y; // BigIntは切り捨て除算
} else {
if (y === 0) throw new Error("Division by zero");
return x / y;
}
},
eq(a, b) {
const [x, y] = toSafeType(a, b);
return x === y;
},
lt(a, b) {
const [x, y] = toSafeType(a, b);
return x < y;
},
gt(a, b) {
const [x, y] = toSafeType(a, b);
return x > y;
},
};
JavaScript
console.log(SafeMath.add(10, 20n)); // 30n (自動で BigInt に変換)
console.log(SafeMath.sub(5n, 2)); // 3n
console.log(SafeMath.mul(10, 2)); // 20
console.log(SafeMath.div(5n, 2)); // 2n(BigInt除算 → 小数切り捨て)
console.log(SafeMath.div(5, 2)); // 2.5(Number除算)
console.log(SafeMath.eq(10n, 10)); // true(自動変換で一致)
console.log(SafeMath.lt(9n, 10)); // true
JavaScript