ordinary-to-primitive.js 705 B

123456789101112131415
  1. var call = require('../internals/function-call');
  2. var isCallable = require('../internals/is-callable');
  3. var isObject = require('../internals/is-object');
  4. var $TypeError = TypeError;
  5. // `OrdinaryToPrimitive` abstract operation
  6. // https://tc39.es/ecma262/#sec-ordinarytoprimitive
  7. module.exports = function (input, pref) {
  8. var fn, val;
  9. if (pref === 'string' && isCallable(fn = input.toString) && !isObject(val = call(fn, input))) return val;
  10. if (isCallable(fn = input.valueOf) && !isObject(val = call(fn, input))) return val;
  11. if (pref !== 'string' && isCallable(fn = input.toString) && !isObject(val = call(fn, input))) return val;
  12. throw $TypeError("Can't convert object to primitive value");
  13. };