-1

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));``` 
2
  • Wrap that loop in another loop... Commented Aug 23, 2022 at 11:07
  • This is not a minimal reproducible example (where's the function)? Why do you loop over conversionChart when num is the actual important thing? Commented Aug 23, 2022 at 11:08

1 Answer 1

0

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));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.