Skip to content

Instantly share code, notes, and snippets.

@markknol
Created July 1, 2024 09:51
Show Gist options
  • Save markknol/c69946d61d587a1827f586e291cc030b to your computer and use it in GitHub Desktop.
Save markknol/c69946d61d587a1827f586e291cc030b to your computer and use it in GitHub Desktop.
Numbers to Roman and visa versa, in JavaScript. Golfed for fun for https://tools23.com/tools/calculation/roman-number-convert/
// source: https://tools23.com/tools/calculation/roman-number-convert/
const m = {M:1000,CM:900,D:500,CD:400,C:100,XC:90,L:50,XL:40,X:10,IX:9,V:5,IV:4,I:1};
const toRoman = n => Object.entries(m).reduce((a,[k,v])=>(a+=k.repeat(n/v|0),n%=v,a),'');
const fromRoman = r => r.match(/CM|CD|XC|XL|IX|IV|\w/g).reduce((o, c) => o + m[c], 0);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment