-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmath.js
95 lines (79 loc) · 1.99 KB
/
math.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
if (! Number.hasOwnProperty('isSafeInteger')) {
Number.MAX_SAFE_INTEGER = 2**53 -1;
Number.MIN_SAFE_INTEGER = -Number.MAX_SAFE_INTEGER;
Number.isSafeInteger = num => num <= Number.MAX_SAFE_INTEGER && num >= Number.MIN_SAFE_INTEGER;
}
if (! Number.hasOwnProperty('EPSILON')) {
Number.EPSILON = 2**-52;
}
if (! Math.hasOwnProperty('sign')) {
Math.sign = x => ((x > 0) - (x < 0)) || +x;
}
if (! Math.hasOwnProperty('trunc')) {
Math.trunc = x => {
const n = x - x%1;
return n===0 && (x<0 || (x===0 && (1/x !== 1/0))) ? -0 : n;
};
}
if (! Math.hasOwnProperty('expm1')) {
Math.expm1 = x => Math.exp(x) - 1;
}
if (! Math.hasOwnProperty('hypot')) {
Math.hypot = (...nums) => Math.sqrt(nums.reduce((sum, num) => sum + num**2, 0));
}
if (! Math.hasOwnProperty('cbrt')) {
Math.cbrt = x => x**(1/3);
}
if (! Math.hasOwnProperty('log10')) {
Math.log10 = x => Math.log(x) * Math.LOG10E;
}
if (! Math.hasOwnProperty('log2')) {
Math.log2 = x => Math.log(x) * Math.LOG2E;
}
if (! Math.hasOwnProperty('log1p')) {
Math.log1p = x => Math.log(1 + x);
}
if (! Math.hasOwnProperty('fround')) {
Math.fround = (function (array) {
return function(x) {
return array[0] = x, array[0];
};
})(new Float32Array(1));
}
if (! (Math.clamp instanceof Function)) {
Math.clamp = function(value, min, max) {
return Math.min(Math.max(value, min), max);
};
}
/*
* Question of if it will be `Math.clamp` or `Math.constrain`
*/
if (! (Math.constrain instanceof Function)) {
Math.constrain = Math.clamp;
}
/**
* @see https://github.com/tc39/proposal-math-sum
*/
if (! (Math.sumPrecise instanceof Function)) {
Math.sumPrecise = function sumPrecise(nums) {
let sum = -0;
for (const num of nums) {
if (! Number.isFinite(num)) {
sum = -0;
break;
} else {
sum += num;
}
}
return sum;
};
}
/**
* @deprecated
*/
if(! (Math.sum instanceof Function)) {
Math.sum = function(...nums) {
console.warn('Math.sum is deprecated. Please use Math.sumPrecise instead.');
return Math.sumPrecise(nums);
};
}