Provide polyfills for missing ES6 math functions

#KT-4900

Rename math.kt to js.math.kt
This commit is contained in:
Ilya Gorbunov
2017-07-20 08:35:39 +03:00
parent 559255f38e
commit e59fbc1097
2 changed files with 99 additions and 1 deletions
@@ -1,6 +1,6 @@
package kotlin.js
//TODO: declare using number
//TODO: deprecate
/**
* Exposes the JavaScript [Math object](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Math) to Kotlin.
*/
@@ -28,6 +28,31 @@ public external object Math {
public fun round(value: Number): Int
public fun floor(value: Number): Int
public fun ceil(value: Number): Int
@PublishedApi
internal fun trunc(value: Number): Double
@PublishedApi
internal fun sign(value: Number): Double
@PublishedApi
internal fun sinh(value: Double): Double
@PublishedApi
internal fun cosh(value: Double): Double
@PublishedApi
internal fun tanh(value: Double): Double
@PublishedApi
internal fun hypot(x: Double, y: Double): Double
@PublishedApi
internal fun expm1(value: Double): Double
@PublishedApi
internal fun log10(value: Double): Double
@PublishedApi
internal fun log2(value: Double): Double
@PublishedApi
internal fun log1p(value: Double): Double
}
/**
+73
View File
@@ -31,6 +31,79 @@ if (typeof String.prototype.endsWith === "undefined") {
return lastIndex !== -1 && lastIndex === position;
};
}
// ES6 Math polyfills
if (typeof Math.sign === "undefined") {
Math.sign = function(x) {
x = +x; // convert to a number
if (x === 0 || isNaN(x)) {
return Number(x);
}
return x > 0 ? 1 : -1;
};
}
if (typeof Math.trunc === "undefined") {
Math.trunc = function(x) {
if (isNaN(x)) {
return NaN;
}
if (x > 0) {
return Math.floor(x);
}
return Math.ceil(x);
};
}
if (typeof Math.sinh === "undefined") {
Math.sinh = function(x) {
var y = Math.exp(x);
return (y - 1 / y) / 2;
};
}
if (typeof Math.cosh === "undefined") {
Math.cosh = function(x) {
var y = Math.exp(x);
return (y + 1 / y) / 2;
};
}
if (typeof Math.tanh === "undefined") {
Math.tanh = function(x){
var a = Math.exp(+x), b = Math.exp(-x);
return a == Infinity ? 1 : b == Infinity ? -1 : (a - b) / (a + b);
};
}
if (typeof Math.hypot === "undefined") {
Math.hypot = function() {
var y = 0;
var length = arguments.length;
for (var i = 0; i < length; i++) {
if (arguments[i] === Infinity || arguments[i] === -Infinity) {
return Infinity;
}
y += arguments[i] * arguments[i];
}
return Math.sqrt(y);
};
}
if (typeof Math.log10 === "undefined") {
Math.log10 = function(x) {
return Math.log(x) * Math.LOG10E;
};
}
if (typeof Math.log2 === "undefined") {
Math.log2 = function(x) {
return Math.log(x) * Math.LOG2E;
};
}
if (typeof Math.log1p === "undefined") {
Math.log1p = function(x) {
return Math.log(x + 1);
};
}
if (typeof Math.expm1 === "undefined") {
Math.expm1 = function(x) {
return Math.exp(x) - 1;
};
}
// For HtmlUnit and PhantomJs
if (typeof ArrayBuffer.isView === "undefined") {
ArrayBuffer.isView = function(a) {