All files / problems/intToRoman index.ts

100% Statements 37/37
100% Branches 6/6
100% Functions 1/1
100% Lines 37/37

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 381x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 5x 5x 5x 5x 5x 5x 5x 5x 69x 69x 55x 69x 14x 14x 14x 69x 5x 5x 1x 1x  
const mapper = {
  1000: "M",
  900: "CM",
  500: "D",
  400: "CD",
  100: "C",
  90: "XC",
  50: "L",
  40: "XL",
  10: "X",
  9: "IX",
  5: "V",
  4: "IV",
  1: "I"
};
 
var romanToInt = function(s: number) {
  let searchNumber = s;
  let result = "";
  let currentIndex = 0;
 
  // sort numbers DESC, [1000, 900, ..., 1]
  const numbers = Object.keys(mapper).map((i) => +i).sort((a, b) => b - a);
 
  while(searchNumber > 0) {
      const currentNumber = numbers[currentIndex];
      if(currentNumber > searchNumber) {
          currentIndex++;
      } else {
          searchNumber = searchNumber - currentNumber;
          result += mapper[currentNumber as keyof typeof mapper];
      }
  }
  return result;
};
 
export default romanToInt;