| Leo Repp | 58b9f11 | 2021-11-22 11:57:47 +0100 | [diff] [blame^] | 1 | 'use strict'; |
| 2 | |
| 3 | var whichBoxedPrimitive = require('which-boxed-primitive'); |
| 4 | var bind = require('function-bind'); |
| 5 | var hasSymbols = require('has-symbols')(); |
| 6 | var hasBigInts = require('has-bigints')(); |
| 7 | |
| 8 | var stringToString = bind.call(Function.call, String.prototype.toString); |
| 9 | var numberValueOf = bind.call(Function.call, Number.prototype.valueOf); |
| 10 | var booleanValueOf = bind.call(Function.call, Boolean.prototype.valueOf); |
| 11 | var symbolValueOf = hasSymbols && bind.call(Function.call, Symbol.prototype.valueOf); |
| 12 | var bigIntValueOf = hasBigInts && bind.call(Function.call, BigInt.prototype.valueOf); |
| 13 | |
| 14 | module.exports = function unboxPrimitive(value) { |
| 15 | var which = whichBoxedPrimitive(value); |
| 16 | if (typeof which !== 'string') { |
| 17 | throw new TypeError(which === null ? 'value is an unboxed primitive' : 'value is a non-boxed-primitive object'); |
| 18 | } |
| 19 | |
| 20 | if (which === 'String') { |
| 21 | return stringToString(value); |
| 22 | } |
| 23 | if (which === 'Number') { |
| 24 | return numberValueOf(value); |
| 25 | } |
| 26 | if (which === 'Boolean') { |
| 27 | return booleanValueOf(value); |
| 28 | } |
| 29 | if (which === 'Symbol') { |
| 30 | if (!hasSymbols) { |
| 31 | throw new EvalError('somehow this environment does not have Symbols, but you have a boxed Symbol value. Please report this!'); |
| 32 | } |
| 33 | return symbolValueOf(value); |
| 34 | } |
| 35 | if (which === 'BigInt') { |
| 36 | return bigIntValueOf(value); |
| 37 | } |
| 38 | throw new RangeError('unknown boxed primitive found: ' + which); |
| 39 | }; |