DEV Community

Discussion on: Solution: Roman to Integer

Collapse
 
alfredosalzillo profile image
Alfredo Salzillo

Kind of a one-liner.
It's better to sum in reverse order.

const romanMap = {
  'I':1,
  'V':5,
  'X':10,  
  'L':50,
  'C':100,
  'D':500,
  'M':1000,
}
const roman = (v) => romanMap[v];
const romanToNumber = (s) => s
    .split('')
    .reverse()
    .map(roman)
    .reduce((
        sum,
        value,
        i,
        { [i - 1]: prev = 0 },
        ) => (sum + Math.sign(value - prev) || 1) * value), 0);
Enter fullscreen mode Exit fullscreen mode
Collapse
 
seanpgallivan profile image
seanpgallivan

The one-liners are never quite as performant as the more standard code, but I do love one-line solutions!

Suggestions: You can simplify/speed up the solution a bit by condensing the .split() and .map(), while converting to a faster 16-bit typed array with Uint16Array.from(). Then, you can also simplify the .reduce() a bit as well.

const romanMap = {
  'I':1,
  'V':5,
  'X':10,  
  'L':50,
  'C':100,
  'D':500,
  'M':1000,
}
const romanToNumber = s => Uint16Array.from(s, n => romanMap[n])
    .reverse()
    .reduce((sum,value) => sum + (value * 4 < sum ? -value : value));
Enter fullscreen mode Exit fullscreen mode