Skip to content

Commit

Permalink
javascript implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
froderik committed Feb 18, 2012
1 parent 90088b6 commit ba46465
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 1 deletion.
5 changes: 4 additions & 1 deletion README.markdown
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,11 @@ This repo is a collection of implementations of the roman numeral kata in differ
## java
* java 1.6.0.17 that comes with MacOSX 10.6.5. Any Java version will probably work fine.

## javascript
* `sudo brew install node`

## ruby
* 1.9.2 instaled with rvm - should probably run with 1.8 as well

## scala
* java 1.6, Scala 2.9.0 and SBT 0.7.7
* java 1.6, Scala 2.9.0 and SBT 0.7.7
2 changes: 2 additions & 0 deletions javascript/numeral_to_roman
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
#!/bin/bash
node numeral_to_roman.js $1
44 changes: 44 additions & 0 deletions javascript/numeral_to_roman.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
var times = function(c, count){
result = ''
for (i = 0; i < count; i++){
result += c
}
return result;
}

var singular_number = function(number, ones_sign, fives_sign, tens_sign){
switch(number){
case 0:
return ''
case 1:
case 2:
case 3:
return times(ones_sign, number)
case 4:
return ones_sign + fives_sign
case 5:
return fives_sign
case 6:
case 7:
case 8:
return fives_sign + times( ones_sign, number - 5 )
case 9:
return ones_sign + tens_sign
}
}

var numeral_to_roman = function(number){
var thousands = Math.floor(number / 1000) % 10
var hundreds = Math.floor(number / 100 ) % 10
var tens = Math.floor(number / 10 ) % 10
var ones = number % 10

var roman_thousands = times('M', thousands)
var roman_hundreds = singular_number( hundreds, 'C', 'D', 'M')
var roman_tens = singular_number( tens, 'X', 'L', 'C')
var roman_ones = singular_number( ones, 'I', 'V', 'X')

console.log('' + roman_thousands + roman_hundreds + roman_tens + roman_ones)
}

numeral_to_roman(process.argv[2]);

0 comments on commit ba46465

Please sign in to comment.