to-primitive.js 1.0 KB

1234567891011121314151617181920212223242526
  1. var global = require('../internals/global');
  2. var call = require('../internals/function-call');
  3. var isObject = require('../internals/is-object');
  4. var isSymbol = require('../internals/is-symbol');
  5. var getMethod = require('../internals/get-method');
  6. var ordinaryToPrimitive = require('../internals/ordinary-to-primitive');
  7. var wellKnownSymbol = require('../internals/well-known-symbol');
  8. var TypeError = global.TypeError;
  9. var TO_PRIMITIVE = wellKnownSymbol('toPrimitive');
  10. // `ToPrimitive` abstract operation
  11. // https://tc39.es/ecma262/#sec-toprimitive
  12. module.exports = function (input, pref) {
  13. if (!isObject(input) || isSymbol(input)) return input;
  14. var exoticToPrim = getMethod(input, TO_PRIMITIVE);
  15. var result;
  16. if (exoticToPrim) {
  17. if (pref === undefined) pref = 'default';
  18. result = call(exoticToPrim, input, pref);
  19. if (!isObject(result) || isSymbol(result)) return result;
  20. throw TypeError("Can't convert object to primitive value");
  21. }
  22. if (pref === undefined) pref = 'number';
  23. return ordinaryToPrimitive(input, pref);
  24. };