Skip to content

Instantly share code, notes, and snippets.

@tuan
Created June 10, 2016 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tuan/c587e5f91b4264175f0a341ac086e52f to your computer and use it in GitHub Desktop.
Save tuan/c587e5f91b4264175f0a341ac086e52f to your computer and use it in GitHub Desktop.
const RomanNumerals = {
1000: 'M',
500: 'D',
100: 'C',
50: 'L',
10: 'X',
5: 'V',
1: 'I'
};
const DescendingBase10Values = Object.keys(RomanNumerals).sort((a, b) => b - a);
const LongToShort = {
'DCCCC': 'CM', // 900
'CCCC': 'CD', // 400
'LXXXX': 'XC', // 90
'XXXX': 'XL', // 40
'VIIII': 'IX', // 9
'IIII': 'IV' // 4
};
const ShortToLong = Object.keys(LongToShort).reduce((accumulator, currentKey) => {
return Object.assign(accumulator, {
[LongToShort[currentKey]]: currentKey
});
}, {});
console.log(ShortToLong);
const convertToAdditiveForm = (value) => {
let result = '';
DescendingBase10Values.reduce((toBeConverted, currentBase10Value) => {
const [numberOfLetters, toBeConvertedNext] = [toBeConverted / currentBase10Value, toBeConverted % currentBase10Value];
result += RomanNumerals[currentBase10Value].repeat(numberOfLetters);
return toBeConvertedNext;
},
value);
return result;
};
console.log(convertToAdditiveForm(14));
const convert = (map) => (roman) => {
return Object.keys(map).reduce((result, currentAlternateForm) => {
return result.replace(currentAlternateForm, map[currentAlternateForm]);
},
roman);
};
const additiveToSubtractive = convert(LongToShort);
const subtractiveToAdditive = convert(ShortToLong);
console.log(subtractiveToAdditive(additiveToSubtractive(convertToAdditiveForm(14))));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment