es6.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. };
  36. // http://www.ecma-international.org/ecma-262/6.0/#sec-toprimitive
  37. module.exports = function ToPrimitive(input, PreferredType) {
  38. if (isPrimitive(input)) {
  39. return input;
  40. }
  41. var hint = 'default';
  42. if (arguments.length > 1) {
  43. if (PreferredType === String) {
  44. hint = 'string';
  45. } else if (PreferredType === Number) {
  46. hint = 'number';
  47. }
  48. }
  49. var exoticToPrim;
  50. if (hasSymbols) {
  51. if (Symbol.toPrimitive) {
  52. exoticToPrim = GetMethod(input, Symbol.toPrimitive);
  53. } else if (isSymbol(input)) {
  54. exoticToPrim = Symbol.prototype.valueOf;
  55. }
  56. }
  57. if (typeof exoticToPrim !== 'undefined') {
  58. var result = exoticToPrim.call(input, hint);
  59. if (isPrimitive(result)) {
  60. return result;
  61. }
  62. throw new TypeError('unable to convert exotic object to primitive');
  63. }
  64. if (hint === 'default' && (isDate(input) || isSymbol(input))) {
  65. hint = 'string';
  66. }
  67. return ordinaryToPrimitive(input, hint === 'default' ? 'number' : hint);
  68. };