* Translates number from given system to decimal. * @protected * @param {string} type Numeral system to translate from * @param {string} string String representation * @return {Number|BigInt|null} Number, BigInt or null, if not defined
(type, string)
| 124 | * @return {Number|BigInt|null} Number, BigInt or null, if not defined |
| 125 | */ |
| 126 | static decodeNumber (type, string) { |
| 127 | // If BigInt is available, use it to treat arbitrarily large integers |
| 128 | if (typeof BigInt !== 'undefined') { |
| 129 | // See https://github.com/tc39/proposal-bigint/issues/86#issuecomment-348317283 |
| 130 | switch (type) { |
| 131 | case 'binary': |
| 132 | return BigInt(`0b${string}`) |
| 133 | case 'octal': |
| 134 | return BigInt(`0o${string}`) |
| 135 | case 'decimal': |
| 136 | return BigInt(string) |
| 137 | case 'hexadecimal': |
| 138 | return BigInt(`0x${string}`) |
| 139 | } |
| 140 | } |
| 141 | |
| 142 | // Fallback to limited JavaScript Numbers |
| 143 | let number = null |
| 144 | switch (type) { |
| 145 | case 'binary': |
| 146 | number = parseInt(string, 2) |
| 147 | break |
| 148 | case 'octal': |
| 149 | number = parseInt(string, 8) |
| 150 | break |
| 151 | case 'decimal': |
| 152 | number = parseInt(string, 10) |
| 153 | break |
| 154 | case 'hexadecimal': |
| 155 | number = parseInt(string, 16) |
| 156 | break |
| 157 | case 'roman-numerals': |
| 158 | number = NumeralSystemEncoder.romanNumeralsToDecimal(string) |
| 159 | break |
| 160 | } |
| 161 | |
| 162 | // Check for successful |
| 163 | if (number === null || isNaN(number)) { |
| 164 | return null |
| 165 | } |
| 166 | |
| 167 | // Validate Number limits |
| 168 | if (!NumeralSystemEncoder.isSafeInteger(number)) { |
| 169 | throw new InvalidInputError( |
| 170 | `Can't read '${string}' because the current environment does not ` + |
| 171 | 'support arbitrarily large integers.') |
| 172 | } |
| 173 | |
| 174 | return number |
| 175 | } |
| 176 | |
| 177 | /** |
| 178 | * Exports number in the given system. |
no test coverage detected