UNPKG

tough-rational

Version:

Rational class using BigInt with fallback to bignumber.js

36 lines (31 loc) 973 B
'use strict'; const { isRational } = require('../fixtures'); const BN = require('bignumber.js'); const bufferToHex = require('../util/buffer-to-hex'); const isBuffer = require('../util/is-buffer'); const coerceToParseable = (input) => { if (isBuffer(input)) return bufferToHex(input); if (isRational(input)) return input._getEncapsulatedRational ? input._getEncapsulatedRational() : new BN(String(input._getNumerator())).dividedBy(String(input._getDenominator())); switch (typeof input) { case 'string': case 'number': return input; case 'undefined': return 0; case 'object': if (input === null) return 0; return input; case 'symbol': return String(input); case 'bigint': return Number(input); case 'boolean': return input ? 1 : 0; } return input; }; const parseDynamic = (input) => new BN(coerceToParseable(input)); Object.assign(module.exports, { coerceToParseable, parseDynamic });