DEV Community

Discussion on: Understanding js reduce with Roman Numerals

 
dannyengelman profile image
Danny Engelman

It can be made easier to read:

const romanToArabic = (input) => [...input].reduceRight((
  acc,
  letter,
  idx,
  arr,
  value = {m:1000, d:500, c:100, l:50, x:10, v:5, i:1}[letter.toLowerCase()],
  doubleSubtraction = letter == arr[idx + 1] // ignore IIX notation
 ) => {
  if (value < acc.high && !doubleSubtraction) { 
    acc.Arabic -= value;
  } else {
    acc.high = value;
    acc.Arabic += value;
  }
  console.log(idx, letter, acc, 'value:', value, acc.high, arr[idx + 1]);
  return acc;
}, { high: 0, Arabic: 0 }).Arabic; // return Arabic value
Enter fullscreen mode Exit fullscreen mode


`