blob: f5e9f3b545bd3a9d886d3d2a089fadc7f8a4d882 [file] [log] [blame]
Leo Repp58b9f112021-11-22 11:57:47 +01001'use strict';
2
3var whichBoxedPrimitive = require('which-boxed-primitive');
4var bind = require('function-bind');
5var hasSymbols = require('has-symbols')();
6var hasBigInts = require('has-bigints')();
7
8var stringToString = bind.call(Function.call, String.prototype.toString);
9var numberValueOf = bind.call(Function.call, Number.prototype.valueOf);
10var booleanValueOf = bind.call(Function.call, Boolean.prototype.valueOf);
11var symbolValueOf = hasSymbols && bind.call(Function.call, Symbol.prototype.valueOf);
12var bigIntValueOf = hasBigInts && bind.call(Function.call, BigInt.prototype.valueOf);
13
14module.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};