-
Notifications
You must be signed in to change notification settings - Fork 3
/
romans.js
69 lines (65 loc) · 1.55 KB
/
romans.js
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
const roman_map = {
M: 1000,
CM: 900,
D: 500,
CD: 400,
C: 100,
XC: 90,
L: 50,
XL: 40,
X: 10,
IX: 9,
V: 5,
IV: 4,
I: 1
}
const allChars = Object.keys(roman_map)
const allNumerals = Object.values(roman_map)
const romanPattern =
/^(M{1,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})|M{0,4}(CM|C?D|D?C{1,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})|M{0,4}(CM|CD|D?C{0,3})(XC|X?L|L?X{1,3})(IX|IV|V?I{0,3})|M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|I?V|V?I{1,3}))$/
const romanize = (decimal) => {
if (
decimal <= 0 ||
typeof decimal !== 'number' ||
Math.floor(decimal) !== decimal
) {
throw new Error('requires an unsigned integer')
}
if (decimal >= 4000) {
throw new Error('requires max value of less than 3999 or less')
}
let roman = ''
for (let i = 0; i < allChars.length; i++) {
while (decimal >= allNumerals[i]) {
decimal -= allNumerals[i]
roman += allChars[i]
}
}
return roman
}
const deromanize = (romanStr) => {
if (typeof romanStr !== 'string') {
throw new Error('requires a string')
}
if (!romanPattern.test(romanStr)) {
throw new Error('requires valid roman numeral string')
}
let romanString = romanStr.toUpperCase()
let arabic = 0
let iteration = romanString.length
while (iteration--) {
let cumulative = roman_map[romanString[iteration]]
if (cumulative < roman_map[romanString[iteration + 1]]) {
arabic -= cumulative
} else {
arabic += cumulative
}
}
return arabic
}
module.exports = {
deromanize,
romanize,
allChars,
allNumerals
}