mirror of
https://github.com/CorentinTh/it-tools.git
synced 2025-05-03 04:49:13 -04:00
feat(tool): roman-arabic numbers converter
This commit is contained in:
parent
3ae61147a9
commit
655019cf23
5 changed files with 154 additions and 0 deletions
|
@ -0,0 +1,18 @@
|
|||
export function arabicToRoman(num: number) {
|
||||
if (num < 1) return '';
|
||||
|
||||
const lookup: { [key: string]: number } = { 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 };
|
||||
let roman = '';
|
||||
for (const i in lookup) {
|
||||
while (num >= lookup[i]) {
|
||||
roman += i;
|
||||
num -= lookup[i];
|
||||
}
|
||||
}
|
||||
return roman;
|
||||
}
|
||||
|
||||
export function romanToArabic(s: string) {
|
||||
const map: { [key: string]: number } = { I: 1, V: 5, X: 10, L: 50, C: 100, D: 500, M: 1000 };
|
||||
return [...s].reduce((r, c, i, s) => (map[s[i + 1]] > map[c] ? r - map[c] : r + map[c]), 0);
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue