Last active
December 20, 2015 23:49
-
-
Save j1n3l0/6215727 to your computer and use it in GitHub Desktop.
Roman -> Arabic converter
This file contains 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
var assert = require("assert") | |
var arabic_for_roman = function(roman) { | |
var arabic_value_for = { | |
"I" : 1, | |
"V" : 5, | |
"X" : 10, | |
"L" : 50, | |
"C" : 100, | |
"D" : 500, | |
"M" : 1000, | |
}; | |
var arabic = 0; | |
for (var i = 0; i < roman.length; i++) { | |
var current = arabic_value_for[roman[i]]; | |
var next = arabic_value_for[roman[i+1]]; | |
if (next > current) { | |
arabic -= current; | |
} else { | |
arabic += current; | |
} | |
} | |
return arabic; | |
} | |
var expected_value = { | |
"I" : 1, | |
"II" : 2, | |
"III" : 3, | |
"IV" : 4, | |
"V" : 5, | |
"VI" : 6, | |
"IX" : 9, | |
"X" : 10, | |
"XV" : 15, | |
"XX" : 20, | |
"XXX" : 30, | |
"L" : 50, | |
"LXVI" : 66, | |
"C" : 100, | |
"D" : 500, | |
"CMXLVI" : 946, | |
"M" : 1000, | |
} | |
describe('arabic_for_roman converter', function() { | |
Object.keys(expected_value).forEach(function (key) { | |
it('should return ' + expected_value[key] + ' for ' + key, function() { | |
assert.equal(expected_value[key], arabic_for_roman(key)) | |
}) | |
}) | |
}) | |
// Now depending on the rules you go by, these may be treated as errors. | |
// This implementation will however work out reasonable values for them. | |
// { | |
// "VV" : 10, | |
// "LL" : 100, | |
// "DDD" : 1500, | |
// "CMDCCXLVI" : 1646, | |
// } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment