OrdinaryToPrimitive.js 1018 B

123456789101112131415161718192021222324252627282930313233343536
  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 Type = require('./Type');
  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 (Type(O) !== 'Object') {
  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 (Type(result) !== 'Object') {
  23. return result;
  24. }
  25. }
  26. }
  27. throw new $TypeError('No primitive value for ' + inspect(O));
  28. };