Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Avatar for KuCalc : devops.
Download
50655 views
1
'use strict';
2
3
var hasSymbols = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol';
4
5
var isPrimitive = require('./helpers/isPrimitive');
6
var isCallable = require('is-callable');
7
var isDate = require('is-date-object');
8
var isSymbol = require('is-symbol');
9
10
var 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
31
var 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
};
40
41
// http://www.ecma-international.org/ecma-262/6.0/#sec-toprimitive
42
module.exports = function ToPrimitive(input, PreferredType) {
43
if (isPrimitive(input)) {
44
return input;
45
}
46
var hint = 'default';
47
if (arguments.length > 1) {
48
if (PreferredType === String) {
49
hint = 'string';
50
} else if (PreferredType === Number) {
51
hint = 'number';
52
}
53
}
54
55
var exoticToPrim;
56
if (hasSymbols) {
57
if (Symbol.toPrimitive) {
58
exoticToPrim = GetMethod(input, Symbol.toPrimitive);
59
} else if (isSymbol(input)) {
60
exoticToPrim = Symbol.prototype.valueOf;
61
}
62
}
63
if (typeof exoticToPrim !== 'undefined') {
64
var result = exoticToPrim.call(input, hint);
65
if (isPrimitive(result)) {
66
return result;
67
}
68
throw new TypeError('unable to convert exotic object to primitive');
69
}
70
if (hint === 'default' && (isDate(input) || isSymbol(input))) {
71
hint = 'string';
72
}
73
return ordinaryToPrimitive(input, hint === 'default' ? 'number' : hint);
74
};
75
76