Last active
December 28, 2017 01:06
-
-
Save iAmWillShepherd/dae8b82c8aa8deb07d10a40bd1b7250f to your computer and use it in GitHub Desktop.
Some code to do stuff
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
interface RomanNumeral { | |
readonly number: number | |
readonly numeral: string | |
} | |
const romanNumerals = [ | |
{ number: 1, numeral: "I" }, | |
{ number: 4, numeral: "IV" }, | |
{ number: 5, numeral: "V" }, | |
{ number: 9, numeral: "IX" }, | |
{ number: 10, numeral: "X" }, | |
{ number: 40, numeral: "XL" }, | |
{ number: 50, numeral: "L" }, | |
{ number: 90, numeral: "XC" }, | |
{ number: 100, numeral: "C" }, | |
{ number: 400, numeral: "CD" }, | |
{ number: 500, numeral: "D" }, | |
{ number: 900, numeral: "CM" }, | |
{ number: 1000, numeral: "M" } | |
] | |
function findBefore<T>(arr: ReadonlyArray<T>, predicate: (item: T) => boolean): T | null { | |
let result: T | null = null | |
for (let element of arr) { | |
if (predicate(element)) { | |
result = element | |
} | |
} | |
return result | |
} | |
function decimalToRomanNumeral(n: number, acc: string = "") { | |
if (n <= 0) { | |
return acc | |
} | |
let maxNumeral: RomanNumeral = findBefore<RomanNumeral>(romanNumerals, rn => rn.number <= n) | |
return decimalToRomanNumeral(n - maxNumeral.number, acc + maxNumeral.numeral) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment