OrdinaryToPrimitive.js 1.0 KB

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