[d565449] | 1 | 'use strict';
|
---|
| 2 |
|
---|
| 3 | var whichBoxedPrimitive = require('which-boxed-primitive');
|
---|
[79a0317] | 4 | var callBound = require('call-bound');
|
---|
[d565449] | 5 | var hasSymbols = require('has-symbols')();
|
---|
| 6 | var hasBigInts = require('has-bigints')();
|
---|
| 7 |
|
---|
| 8 | var stringToString = callBound('String.prototype.toString');
|
---|
| 9 | var numberValueOf = callBound('Number.prototype.valueOf');
|
---|
| 10 | var booleanValueOf = callBound('Boolean.prototype.valueOf');
|
---|
| 11 | var symbolValueOf = hasSymbols && callBound('Symbol.prototype.valueOf');
|
---|
| 12 | var bigIntValueOf = hasBigInts && callBound('BigInt.prototype.valueOf');
|
---|
| 13 |
|
---|
[79a0317] | 14 | /** @type {import('.')} */
|
---|
[d565449] | 15 | module.exports = function unboxPrimitive(value) {
|
---|
| 16 | var which = whichBoxedPrimitive(value);
|
---|
| 17 | if (typeof which !== 'string') {
|
---|
| 18 | throw new TypeError(which === null ? 'value is an unboxed primitive' : 'value is a non-boxed-primitive object');
|
---|
| 19 | }
|
---|
| 20 |
|
---|
| 21 | if (which === 'String') {
|
---|
| 22 | return stringToString(value);
|
---|
| 23 | }
|
---|
| 24 | if (which === 'Number') {
|
---|
| 25 | return numberValueOf(value);
|
---|
| 26 | }
|
---|
| 27 | if (which === 'Boolean') {
|
---|
| 28 | return booleanValueOf(value);
|
---|
| 29 | }
|
---|
| 30 | if (which === 'Symbol') {
|
---|
| 31 | if (!hasSymbols) {
|
---|
| 32 | throw new EvalError('somehow this environment does not have Symbols, but you have a boxed Symbol value. Please report this!');
|
---|
| 33 | }
|
---|
[79a0317] | 34 | // eslint-disable-next-line no-extra-parens
|
---|
| 35 | return /** @type {Exclude<typeof symbolValueOf, false>} */ (symbolValueOf)(value);
|
---|
[d565449] | 36 | }
|
---|
| 37 | if (which === 'BigInt') {
|
---|
[79a0317] | 38 | // eslint-disable-next-line no-extra-parens
|
---|
| 39 | return /** @type {Exclude<typeof bigIntValueOf, false>} */ (bigIntValueOf)(value);
|
---|
[d565449] | 40 | }
|
---|
| 41 | throw new RangeError('unknown boxed primitive found: ' + which);
|
---|
| 42 | };
|
---|