-
-
Notifications
You must be signed in to change notification settings - Fork 184
Expand file tree
/
Copy pathParseInt.ts
More file actions
41 lines (34 loc) · 1.31 KB
/
ParseInt.ts
File metadata and controls
41 lines (34 loc) · 1.31 KB
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
import { __TS__Match } from "./Match";
const parseIntBasePattern = "0123456789aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTvVwWxXyYzZ";
export function __TS__ParseInt(this: void, numberString: string, base?: number): number {
// Check which base to use if none specified
if (base === undefined) {
base = 10;
const [hexMatch] = __TS__Match(numberString, "^%s*-?0[xX]");
if (hexMatch !== undefined) {
base = 16;
numberString = __TS__Match(hexMatch, "-")[0]
? "-" + numberString.substring(hexMatch.length)
: numberString.substring(hexMatch.length);
}
}
// Check if base is in bounds
if (base < 2 || base > 36) {
return NaN;
}
// Calculate string match pattern to use
const allowedDigits =
base <= 10 ? parseIntBasePattern.substring(0, base) : parseIntBasePattern.substring(0, 10 + 2 * (base - 10));
const pattern = `^%s*(-?[${allowedDigits}]*)`;
// Try to parse with Lua tonumber
const number = tonumber(__TS__Match(numberString, pattern)[0], base);
if (number === undefined) {
return NaN;
}
// Lua uses a different floor convention for negative numbers than JS
if (number >= 0) {
return math.floor(number);
} else {
return math.ceil(number);
}
}