OrdinaryToPrimitive.js 1020 B

12345678910111213141516171819202122232425262728293031323334353637
  1. 'use strict';
  2. var $TypeError = require('es-errors/type');
  3. var Call = require('./Call');
  4. var Get = require('./Get');
  5. var IsCallable = require('./IsCallable');
  6. var isObject = require('../helpers/isObject');
  7. var inspect = require('object-inspect');
  8. // https://262.ecma-international.org/8.0/#sec-ordinarytoprimitive
  9. module.exports = function OrdinaryToPrimitive(O, hint) {
  10. if (!isObject(O)) {
  11. throw new $TypeError('Assertion failed: Type(O) is not Object');
  12. }
  13. if (/* typeof hint !== 'string' || */ hint !== 'string' && hint !== 'number') {
  14. throw new $TypeError('Assertion failed: `hint` must be "string" or "number"');
  15. }
  16. var methodNames = hint === 'string' ? ['toString', 'valueOf'] : ['valueOf', 'toString'];
  17. for (var i = 0; i < methodNames.length; i += 1) {
  18. var name = methodNames[i];
  19. var method = Get(O, name);
  20. if (IsCallable(method)) {
  21. var result = Call(method, O);
  22. if (!isObject(result)) {
  23. return result;
  24. }
  25. }
  26. }
  27. throw new $TypeError('No primitive value for ' + inspect(O));
  28. };