Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/LuaLib.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ export enum LuaLibFeature {
MathAtan2 = "MathAtan2",
MathModf = "MathModf",
MathSign = "MathSign",
MathTrunc = "MathTrunc",
New = "New",
Number = "Number",
NumberIsFinite = "NumberIsFinite",
Expand Down
14 changes: 10 additions & 4 deletions src/lualib/MathSign.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,15 @@
// https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-math.sign

import { __TS__NumberIsNaN } from "./NumberIsNaN";

export function __TS__MathSign(this: void, val: number) {
if (val > 0) {
return 1;
} else if (val < 0) {
if (__TS__NumberIsNaN(val) || val === 0) {
return val;
}

if (val < 0) {
return -1;
}

return 0;
return 1;
}
10 changes: 10 additions & 0 deletions src/lualib/MathTrunc.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
// https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-math.trunc

import { __TS__NumberIsFinite } from "./NumberIsFinite";
export function __TS__MathTrunc(this: void, val: number) {
if (!__TS__NumberIsFinite(val) || val === 0) {
return val;
}

return val > 0 ? math.floor(val) : math.ceil(val);
}
4 changes: 4 additions & 0 deletions src/transformation/builtins/math.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,10 @@ export function transformMathCall(
return transformLuaLibFunction(context, LuaLibFeature.MathSign, node, ...params);
}

case "trunc": {
return transformLuaLibFunction(context, LuaLibFeature.MathTrunc, node, ...params);
}

case "abs":
case "acos":
case "asin":
Expand Down
15 changes: 14 additions & 1 deletion test/unit/builtins/math.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,12 @@ test.each([
// sqrt
"Math.sqrt(2)",
"Math.sqrt(-2)",
// trunc
"Math.trunc(42.42)",
"Math.trunc(-42.42)",
"Math.trunc(0)",
"Math.trunc(Infinity)",
"Math.trunc(-Infinity)",
])("%s", code => {
util.testExpression(code).expectToMatchJsResult();
});
Expand All @@ -65,7 +71,14 @@ test.each(["E", "LN10", "LN2", "LOG10E", "LOG2E", "SQRT1_2", "SQRT2"])("Math.%s"
});

// LuaLib MathSign
test.each(["Math.sign(-42)", "Math.sign(42)", "Math.sign(-4.2)", "Math.sign(4.2)", "Math.sign(0)"])("%s", code => {
test.each([
"Math.sign(-42)",
"Math.sign(42)",
"Math.sign(-4.2)",
"Math.sign(4.2)",
"Math.sign(0)",
"Math.sign(-Infinity)",
])("%s", code => {
util.testExpression(code).expectToMatchJsResult();
});

Expand Down