ordinary-to-primitive.js 755 B

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