index.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. 'use strict';
  2. var whichBoxedPrimitive = require('which-boxed-primitive');
  3. var bind = require('function-bind');
  4. var hasSymbols = require('has-symbols')();
  5. var hasBigInts = require('has-bigints')();
  6. var stringToString = bind.call(Function.call, String.prototype.toString);
  7. var numberValueOf = bind.call(Function.call, Number.prototype.valueOf);
  8. var booleanValueOf = bind.call(Function.call, Boolean.prototype.valueOf);
  9. var symbolValueOf = hasSymbols && bind.call(Function.call, Symbol.prototype.valueOf);
  10. var bigIntValueOf = hasBigInts && bind.call(Function.call, 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. };