DEV Community

Discussion on: Daily Challenge #209 - Roman Numerals

Collapse
 
empereol profile image
Empereol • Edited

TypeScript

type RomanNumeral = 'I' | 'V' | 'X' | 'L' | 'C' | 'D' | 'M';

const RomanNumerals: Record<RomanNumeral, number> = {
  I: 1,
  V: 5,
  X: 10,
  L: 50,
  C: 100,
  D: 500,
  M: 1000
};

/**
 * Convert a string of Roman Numerals to an integer
 * @param input String of Roman Numerals. Invalid characters are not considered.
 */
function solution(input: string): number {
  return Array.from(input)
    .map(n => RomanNumerals[n])
    .filter(Number)
    .reduce((total, val, idx, arr) => {
      if (val >= (arr[idx + 1] || 0)) {
        return (total += val);
      } else {
        return (total -= val);
      }
    }, 0);
}