Created
March 4, 2020 10:07
-
-
Save FanchGadjo/039aabfd81db91a20e0808188229cd36 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Coded and shared on Twitter by Florin Pop | |
// https://twitter.com/florinpop1705/status/1234951601842016256 | |
// Create a RomanNumerals class that can convert | |
// a roman numeral to and from an integer value. | |
const rom = { | |
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 RomanNumerals = { | |
toRoman(num) { | |
let res = ""; | |
Object.keys(rom).forEach(key => { | |
while (num >= rom[key]) { | |
num -= rom[key]; | |
res += key; | |
} | |
}); | |
return res; | |
}, | |
fromRoman(roman) { | |
let res = 0; | |
const arr = roman.split(""); | |
for (let i = 0; i < arr.length; i++) { | |
let keyA = arr[i]; | |
let keyB = arr[i + 1]; | |
if (rom[keyA] < rom[keyB]) { | |
res += rom[keyA + keyB]; | |
i++; | |
} else { | |
res += rom[keyA]; | |
} | |
} | |
return res; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment