Skip to content

Instantly share code, notes, and snippets.

@edalorzo
Created February 10, 2018 13:12
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save edalorzo/e07d46fdf39f26291e642c6a8fa5a8e0 to your computer and use it in GitHub Desktop.
asDecimal = function(){
var romans = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000 };
return function(roman){
return roman.split('').map(function(r){ return romans[r];})
.reduce(function(res,n,i,digits){
var prev = i > 0 ? digits[i-1] : 0;
return prev < n ? res + n - 2 * prev : res + n;
},0);
};
}();
console.log(asDecimal("MCMLXXVIII")); //1978
console.log(asDecimal("CCCLXIX")); //369
console.log(asDecimal("MMDCCLI")); //2751
console.log(asDecimal("MMMCMXCIX")); //3999
asRoman = function(){
var romans = [
["I","II","III","IV","V","VI","VII","VIII","IX"],
["X","XX","XXX","XL","L","LX","LXX","LXXX","XC"],
["C","CC","CCC","CD","D","DC","DCC","DCCC","CM"],
["M","MM","MMM"]
];
return function(number){
return number.toString()
.split("").reverse()
.map(function(s){ return parseInt(s); })
.reduce(function(acc,n,idx,arr){ return n > 0 ? romans[idx][n-1] + acc : acc;},"");
};
}();
console.log(asRoman(2008));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment