This repository has been archived by the owner on Jan 12, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
common.ts
82 lines (72 loc) · 2.06 KB
/
common.ts
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
import * as fs from "fs";
/**
* source https://stackoverflow.com/a/60203932
*/
export const readLineSync = () => {
let rtnval = "";
const buffer = Buffer.alloc ? Buffer.alloc(1) : new Buffer(1);
for (; ;) {
fs.readSync(0, buffer, 0, 1, undefined); // 0 is fd for stdin
if (buffer[0] === 10) { // LF \n return on line feed
break;
} else if (buffer[0] !== 13) { // CR \r skip carriage return
rtnval += buffer.toString();
}
}
return rtnval;
};
export const readIntSync = (): number => {
let num: number = NaN;
while (true) {
const res = readLineSync();
num = Number.parseInt(res, 10);
if (Number.isNaN(num))
// tslint:disable-next-line: no-console
console.error("zadaná hodnota není číslo, zkus to znovu");
else break;
}
return num;
};
export const formatString = (str: string, args: number[]): string => {
const split = str.split(/(%)([0-9]*)([idxXc])/);
let curI = 0;
while (curI < split.length && args.length) {
const curStr = split[curI];
if (curStr === "%") {
const padding = Number.parseInt(split[curI + 1], 10) || 0;
const style = split[curI + 2] as "i" | "d" | "x" | "X" | "c";
let formatedRes: string;
const num = args.pop();
switch (style) {
case "x":
formatedRes = num.toString(16);
break;
case "X":
formatedRes = num.toString(16);
formatedRes = formatedRes.toUpperCase();
break;
case "c":
formatedRes = String.fromCharCode(num);
break;
case "d":
case "i":
formatedRes = num.toString();
break;
default:
curI++;
continue;
}
formatedRes = formatedRes.padStart(padding, " ");
split.splice(curI, 3, formatedRes);
}
curI++;
}
return split.join("");
};
export const isBoolean = (obj: any) => {
return obj === true || obj === false;
};
/** helper function for throwing errors inside expressions */
export const throwReturn = <T>(msg: string): T => {
throw new Error(msg);
};