UNPKG

779 BJavaScriptView Raw
1var isObject = require('../internals/is-object');
2
3// `ToPrimitive` abstract operation
4// https://tc39.github.io/ecma262/#sec-toprimitive
5// instead of the ES6 spec version, we didn't implement @@toPrimitive case
6// and the second argument - flag - preferred type is a string
7module.exports = function (input, PREFERRED_STRING) {
8 if (!isObject(input)) return input;
9 var fn, val;
10 if (PREFERRED_STRING && typeof (fn = input.toString) == 'function' && !isObject(val = fn.call(input))) return val;
11 if (typeof (fn = input.valueOf) == 'function' && !isObject(val = fn.call(input))) return val;
12 if (!PREFERRED_STRING && typeof (fn = input.toString) == 'function' && !isObject(val = fn.call(input))) return val;
13 throw TypeError("Can't convert object to primitive value");
14};