index.js 1.5 KB

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