Skip to content

Instantly share code, notes, and snippets.

@codejockie
Last active June 15, 2020 13:08
Show Gist options
  • Select an option

  • Save codejockie/d15d00a5834dcf484e49e9d79844a129 to your computer and use it in GitHub Desktop.

Select an option

Save codejockie/d15d00a5834dcf484e49e9d79844a129 to your computer and use it in GitHub Desktop.
Roman numerals to Arabic numerals
const romanMap: { [key: string]: number } = {
I: 1,
V: 5,
X: 10,
L: 50,
C: 100,
D: 500,
M: 1000,
}
export function romanArabic(roman: string): number {
const chars = roman.toUpperCase().split("")
return chars.reduce((acc: number, char: string, i: number) => {
const previousChar = chars[i - 1]
const isGreater = romanMap[char] > romanMap[previousChar]
return isGreater
? acc -
romanMap[previousChar] +
(romanMap[char] - romanMap[previousChar])
: acc + romanMap[char]
}, 0)
}
@codejockie
Copy link
Copy Markdown
Author

Another method

const romanList: { [key: string]: number } = { CM: 900, M: 1000, CD: 400, D: 500, XC: 90, C: 100, XL: 40, L: 50, IX: 9, X: 10, IV: 4, V: 5, I: 1 }

export function romanArabic(romanNum: string): number {
  let index = 0
  let number = 0
  romanNum = romanNum.toUpperCase()

  for (const key in romanList) {
    index = romanNum.indexOf(key)
    while (index != -1) {
      number += romanList[key]
      romanNum = romanNum.replace(key, "*")
      index = romanNum.indexOf(key)
    }
  }
  return number
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment