Created
June 1, 2024 02:55
-
-
Save hsingtism/76ab60eb92ced189cfb9b41d66ecf75c 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
| const digitKey = [ | |
| "","I","II","III","IV","V","VI","VII","VIII","IX", | |
| "","X","XX","XXX","XL","L","LX","LXX","LXXX","XC", | |
| "","C","CC","CCC","CD","D","DC","DCC","DCCC","CM", | |
| "","M","MM","MMM" | |
| ] | |
| const arabicToRoman = n => n.toString().padStart(4, '0').split('').map((v, i) => digitKey[+v + (3 - i) * 10]).join('') | |
| arabicToRoman.validate = n => Number.isInteger(n) && n > 0 && n < 4000 | |
| const letterKey = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000} | |
| const romanToArabic = s => s.split('') | |
| .reduce((acc, val, i, arr) => letterKey[arr[i+1]] > letterKey[val] ? acc - letterKey[val] : acc + letterKey[val], 0) | |
| romanToArabic.validate = s => /^M{0,3}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$/.test(s) && !!s |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment