0

I am newbie working on the Roman Numeral Kata in Javascript. All specs are passing. I have refactored the spec file and am now trying to refactor the main file.

What used to look like this:

function roman(number) {
  var conversion = ''

  if (number == 100){
    conversion += 'C'
    number -= 100
  }
// omitted code

  while (number >= 1){
   conversion += 'I'
   number -= 1
 }

return conversion
}

Now looks like this:

function roman(number) {

  var denominations = {

    100: 'C',
    // omitted code
    5: 'V',
    4: 'IV',
    1: 'I'

  }

  var conversions = ''

  _.each(denominations, function(roman_num, natural_num) {
    while (number >= natural_num){ 
      conversions = conversions + roman_num
      number -= natural_num
    }
  })
  return conversions
}

I've spent some time debugging using the JS console through Chrome and it looks like instead of iterating through each denomination its just getting stuck at 1.

Also I'm using Jasmine so my errors look like this:

Expected 'IIII' to equal 'IV'
Expected 'IIIII' to equal 'V'

and so on.

So my questions are: 1. Why is it getting stuck only returning the values for 1, 'I' and 2. How do I fix it?

Thanks in advance!

Zero Piraeus
  • 56,143
  • 27
  • 150
  • 160
user3245240
  • 265
  • 4
  • 10

1 Answers1

0

JavaScript object are HashMap with string as index. So the order of the element in your "_.each" isn't garanteed to be the same as declared. You should use structure which garantees the order like Array.

function roman(number) {
  var denominations_natural = [100, 5, 4, 1];
  var denominations_roman = ["C", "V", "IV", "I"];

  var conversions = '';

  for (var i=0; i<denominations_natural.length; i++) {
    while (number >= denominations_natural[i]) {
      conversions += denominations_roman[i];
      number -= denominations_natural[i];
    }
  }

  return conversions;
}
HoLyVieR
  • 10,985
  • 5
  • 42
  • 67