es2015.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. 'use strict';
  2. var hasSymbols = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol';
  3. var isPrimitive = require('./helpers/isPrimitive');
  4. var isCallable = require('is-callable');
  5. var isDate = require('is-date-object');
  6. var isSymbol = require('is-symbol');
  7. var ordinaryToPrimitive = function OrdinaryToPrimitive(O, hint) {
  8. if (typeof O === 'undefined' || O === null) {
  9. throw new TypeError('Cannot call method on ' + O);
  10. }
  11. if (typeof hint !== 'string' || (hint !== 'number' && hint !== 'string')) {
  12. throw new TypeError('hint must be "string" or "number"');
  13. }
  14. var methodNames = hint === 'string' ? ['toString', 'valueOf'] : ['valueOf', 'toString'];
  15. var method, result, i;
  16. for (i = 0; i < methodNames.length; ++i) {
  17. method = O[methodNames[i]];
  18. if (isCallable(method)) {
  19. result = method.call(O);
  20. if (isPrimitive(result)) {
  21. return result;
  22. }
  23. }
  24. }
  25. throw new TypeError('No default value');
  26. };
  27. var GetMethod = function GetMethod(O, P) {
  28. var func = O[P];
  29. if (func !== null && typeof func !== 'undefined') {
  30. if (!isCallable(func)) {
  31. throw new TypeError(func + ' returned for property ' + P + ' of object ' + O + ' is not a function');
  32. }
  33. return func;
  34. }
  35. return void 0;
  36. };
  37. // http://www.ecma-international.org/ecma-262/6.0/#sec-toprimitive
  38. module.exports = function ToPrimitive(input) {
  39. if (isPrimitive(input)) {
  40. return input;
  41. }
  42. var hint = 'default';
  43. if (arguments.length > 1) {
  44. if (arguments[1] === String) {
  45. hint = 'string';
  46. } else if (arguments[1] === Number) {
  47. hint = 'number';
  48. }
  49. }
  50. var exoticToPrim;
  51. if (hasSymbols) {
  52. if (Symbol.toPrimitive) {
  53. exoticToPrim = GetMethod(input, Symbol.toPrimitive);
  54. } else if (isSymbol(input)) {
  55. exoticToPrim = Symbol.prototype.valueOf;
  56. }
  57. }
  58. if (typeof exoticToPrim !== 'undefined') {
  59. var result = exoticToPrim.call(input, hint);
  60. if (isPrimitive(result)) {
  61. return result;
  62. }
  63. throw new TypeError('unable to convert exotic object to primitive');
  64. }
  65. if (hint === 'default' && (isDate(input) || isSymbol(input))) {
  66. hint = 'string';
  67. }
  68. return ordinaryToPrimitive(input, hint === 'default' ? 'number' : hint);
  69. };