index.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. 'use strict';
  2. var whichBoxedPrimitive = require('which-boxed-primitive');
  3. var callBound = require('call-bind/callBound');
  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. module.exports = function unboxPrimitive(value) {
  12. var which = whichBoxedPrimitive(value);
  13. if (typeof which !== 'string') {
  14. throw new TypeError(which === null ? 'value is an unboxed primitive' : 'value is a non-boxed-primitive object');
  15. }
  16. if (which === 'String') {
  17. return stringToString(value);
  18. }
  19. if (which === 'Number') {
  20. return numberValueOf(value);
  21. }
  22. if (which === 'Boolean') {
  23. return booleanValueOf(value);
  24. }
  25. if (which === 'Symbol') {
  26. if (!hasSymbols) {
  27. throw new EvalError('somehow this environment does not have Symbols, but you have a boxed Symbol value. Please report this!');
  28. }
  29. return symbolValueOf(value);
  30. }
  31. if (which === 'BigInt') {
  32. return bigIntValueOf(value);
  33. }
  34. throw new RangeError('unknown boxed primitive found: ' + which);
  35. };