1 min readJun 1, 2020
Thank you for the very nice explanation.
You could refactor your code a little more by scoping the variables closer to where they are used.
Also you could use Array.reduce
to accumulate the total amount.
const map = new Map([
['I', 1],
['V', 5],
['X', 10],
['L', 50],
['C', 100],
['D', 500],
['M', 1000],
]);function romanToInt(s) {
return s.split('').reduce((accumulator, _currentValue, index, arr) => {
const current = map.get(arr[index]) || 0;
const next = map.get(arr[index + 1]) || 0;if (current < next) {
return accumulator - current;
}return accumulator + current;
}, 0);
}