mirror of
https://github.com/CorentinTh/it-tools.git
synced 2025-05-03 04:49:13 -04:00
fix(roman-numeral-converter): input validation and feedback (#332)
* fix(roman-numeral-converter): checks for valid input and conversion enhancements Validates if numeral values are between 1 and 3999999. Validates if a roman number is valid. * fix(roman-numeral-converter): optimize logic for copy button * fix(roman-numeral-converter): changes due to review
This commit is contained in:
parent
076df11024
commit
8930e139b2
3 changed files with 62 additions and 14 deletions
|
@ -1,5 +1,7 @@
|
|||
export const MIN_ARABIC_TO_ROMAN = 1;
|
||||
export const MAX_ARABIC_TO_ROMAN = 3999;
|
||||
export function arabicToRoman(num: number) {
|
||||
if (num < 1) return '';
|
||||
if (num < MIN_ARABIC_TO_ROMAN || num > MAX_ARABIC_TO_ROMAN) return '';
|
||||
|
||||
const lookup: { [key: string]: number } = {
|
||||
M: 1000,
|
||||
|
@ -26,7 +28,16 @@ export function arabicToRoman(num: number) {
|
|||
return roman;
|
||||
}
|
||||
|
||||
const ROMAN_NUMBER_REGEX = new RegExp(/^M{0,3}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$/);
|
||||
|
||||
export function isValidRomanNumber(romanNumber: string) {
|
||||
return ROMAN_NUMBER_REGEX.test(romanNumber);
|
||||
}
|
||||
|
||||
export function romanToArabic(s: string) {
|
||||
if (!isValidRomanNumber(s)) {
|
||||
return null;
|
||||
}
|
||||
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