Search code examples
javascriptalgorithmfor-in-loop

how to restart a for in loop iteration in javascript


I need to restart the loop every time the if statement occurs so that the correct roman numeral conversion works

by pushing the key(roman numeral) of the iterator to counter, and by subtracting the value of the iterator from the input num then I want the loop to start again from the beginning


let conversionChart = {
  m:1000,
  cm:900,
  d:500,
  cd:400,
  c:100,
  xc:90,
  l:50,
  xl:40,
  x:10,
  ix:9,
  v:5,
  iv:4,
  i:1
}

let newArr = [];
let counter = [];

for(let i in conversionChart){
  if(num >= conversionChart[i]){
    counter.push(i)
    num = num - conversionChart[i]
    continue;
    }
   }




 return counter
}

console.log(convertToRoman(36));``` 

Solution

  • You'd need to wrap that loop in another loop that continues for as long as there is something to convert:

    let conversionChart = {
      m: 1000,
      cm: 900,
      d: 500,
      cd: 400,
      c: 100,
      xc: 90,
      l: 50,
      xl: 40,
      x: 10,
      ix: 9,
      v: 5,
      iv: 4,
      i: 1,
    };
    
    function convertToRoman(num) {
      const counter = [];
      // while there is still something to convert...
      while (num > 0) {
        for (let romanNumeral in conversionChart) {
          if (num >= conversionChart[romanNumeral]) {
            counter.push(romanNumeral);
            num = num - conversionChart[romanNumeral];
            break;  // ... out of the inner "romanNumeral ..." loop
          }
        }
      }
      return counter.join("");
    }
    
    console.log(convertToRoman(36));