Created
February 10, 2018 13:12
-
-
Save edalorzo/e07d46fdf39f26291e642c6a8fa5a8e0 to your computer and use it in GitHub Desktop.
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
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