es5.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. 'use strict';
  2. var toStr = Object.prototype.toString;
  3. var isPrimitive = require('./helpers/isPrimitive');
  4. var isCallable = require('is-callable');
  5. // http://ecma-international.org/ecma-262/5.1/#sec-8.12.8
  6. var ES5internalSlots = {
  7. '[[DefaultValue]]': function (O) {
  8. var actualHint;
  9. if (arguments.length > 1) {
  10. actualHint = arguments[1];
  11. } else {
  12. actualHint = toStr.call(O) === '[object Date]' ? String : Number;
  13. }
  14. if (actualHint === String || actualHint === Number) {
  15. var methods = actualHint === String ? ['toString', 'valueOf'] : ['valueOf', 'toString'];
  16. var value, i;
  17. for (i = 0; i < methods.length; ++i) {
  18. if (isCallable(O[methods[i]])) {
  19. value = O[methods[i]]();
  20. if (isPrimitive(value)) {
  21. return value;
  22. }
  23. }
  24. }
  25. throw new TypeError('No default value');
  26. }
  27. throw new TypeError('invalid [[DefaultValue]] hint supplied');
  28. }
  29. };
  30. // http://ecma-international.org/ecma-262/5.1/#sec-9.1
  31. module.exports = function ToPrimitive(input) {
  32. if (isPrimitive(input)) {
  33. return input;
  34. }
  35. if (arguments.length > 1) {
  36. return ES5internalSlots['[[DefaultValue]]'](input, arguments[1]);
  37. }
  38. return ES5internalSlots['[[DefaultValue]]'](input);
  39. };