Created
February 24, 2012 03:56
-
-
Save o-sam-o/1897246 to your computer and use it in GitHub Desktop.
JS Roman Numerals Kata
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function multipleChar(theChar, times){ | |
var result = ""; | |
for(var i = 0;i < times;i++){ | |
result += theChar; | |
} | |
return result; | |
} | |
CHAR_LOOKUP = [ | |
{ | |
"char":"X", | |
"num":10 | |
}, | |
{ | |
"char":"V", | |
"num":5 | |
}, | |
{ | |
"char":"I", | |
"num":1 | |
} | |
] | |
function toRoman(num){ | |
if(num == 0) { | |
return "Nulla"; | |
} | |
var result = "" | |
var previous_char = null; | |
for(var i = 0; i < CHAR_LOOKUP.length; i++){ | |
var current_char = CHAR_LOOKUP[i]; | |
var new_entry = multipleChar(current_char.char, | |
Math.floor(num / current_char.num)); | |
if(new_entry == multipleChar(current_char.char, 4)){ | |
new_entry = current_char.char + previous_char.char; | |
} | |
num = num % current_char.num; | |
result += new_entry; | |
console.log(result); | |
previous_char = current_char; | |
} | |
return result; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
describe('Roman Numeral Kata',function(){ | |
it('0 returns Nulla',function(){ | |
expect(toRoman(0)).toBe('Nulla'); | |
}); | |
it('1 returns I',function(){ | |
expect(toRoman(1)).toBe('I'); | |
}); | |
it('2 returns II',function(){ | |
expect(toRoman(2)).toBe('II'); | |
}); | |
it('5 returns V',function(){ | |
expect(toRoman(5)).toBe('V'); | |
}); | |
it('4 returns IV',function(){ | |
expect(toRoman(4)).toBe('IV'); | |
}); | |
it('10 returns X',function(){ | |
expect(toRoman(10)).toBe('X'); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment