-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathromanNumerals.js
More file actions
64 lines (57 loc) · 1.57 KB
/
romanNumerals.js
File metadata and controls
64 lines (57 loc) · 1.57 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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
class RomanNumerals {
static #romanData = [
[1000, "M"],
[900, "CM"],
[500, "D"],
[400, "CD"],
[100, "C"],
[90, "XC"],
[50, "L"],
[40, "XL"],
[10, "X"],
[9, "IX"],
[5, "V"],
[4, "IV"],
[1, "I"]
];
static toRoman(num) {
let result = "";
if (num <= 0 || num >= 4000) {
throw new RangeError("Invalid Number ", {cause: "Number Wasn't Within The Range"});
}
for (let [val, sym] of this.#romanData) {
while(num >= val) {
result += sym;
num -= val;
}
}
return result;
}
static fromRoman(str) {
str = str.toUpperCase();
let counter = 0;
let result = 0;
let isMatched = false;
while (counter < str.length) {
const twoStr = str.substring(counter, counter + 2);
const oneStr = str.substring(counter, counter + 1);
for (let [val, sym] of this.#romanData) {
if (sym == twoStr) {
counter += 2;
result += val;
isMatched = true;
break;
}else if (sym == oneStr) {
counter += 1;
result += val;
isMatched = true;
break;
}
}
}
if (!isMatched) {
throw new Error("Invalid Roman Numeral Detected:", counter);
}
return result;
}
}