Skip to content

Instantly share code, notes, and snippets.

@WhiskeyTuesday
Created August 24, 2023 01:03
Show Gist options
  • Save WhiskeyTuesday/cc7812cf67a5b9783db0bacbb12daf23 to your computer and use it in GitHub Desktop.
Save WhiskeyTuesday/cc7812cf67a5b9783db0bacbb12daf23 to your computer and use it in GitHub Desktop.
Reverse symbolic romanize
/*
I posted this on twitter (on my old/alternate account) some years ago but
thought I'd preserve it here. Kevlin Henney, in one of his talks, points
out that the decimal to roman numeral kata is often thought of as a
numerical or maths problem but that if you think of it as direct symbol
manipulation (or doing math in unary, which is almost the same thing)
it's a lot easier. All I did was reverse the ordering of the example in a
way that I think makes the logic more clear. Doing it this way without
the grep repetition operators would have been very cumbersome and my guess
is that that's why the original example was ordered the other way.
https://twitter.com/Whiskey2sday/status/1157215416688578562/
AUTHOR - @WhiskeyTuesday
LICENCE - WTFPL 3.1 - https://ph.dtf.wtf/u/wtfplv31 for more details.
*/
const rsr = (n) => (
'I'.repeat(n)
.replace(/I{1000}/g, 'M')
.replace(/I{900}/g, 'CM')
.replace(/I{500}/g, 'D')
.replace(/I{400}/g, 'CD')
.replace(/I{100}/g, 'C')
.replace(/I{90}/g, 'XC')
.replace(/I{50}/g, 'L')
.replace(/I{40}/g, 'XL')
.replace(/I{10}/g, 'X')
.replace(/I{9}/g, 'IX')
.replace(/I{5}/g, 'V')
.replace(/I{4}/g, 'IV')
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment