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