to-primitive.js 1001 B

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