Arabic to Roman Numerals Shortcode
I’ve always used Roman numerals for the years on my work and in the footer of this site. Perhaps it’s annoying, pretentious, and dumb, but whatever. That’s not the point of this post. The point is I made an Eleventy shortcode to convert Arabic numerals to the Roman numerals we all have to think about the read.
When I want to use a Roman numerals I use {% romanNumeral 1996 %}
and that gets converted to MCMXCVI
(I used the short code here, but you can't see it because it worked). Sure, I only use it twice on the site, in the footer and in the sentence before this, but I won't have to think about. The only time I need to change the year is on January 1st. For that I use a variable, {% assign year = 'now' | date: '%Y' %}
, which uses the date at build time. I use Netlify, so to update that I use the Netlify CLI. netlify deploy --trigger
triggers a deploy. I like making simple things complicated and cool.
In my Eleventy config file (.eleventy.js
in my case) I import it at the top and then add the shortcode.
const romanNumeral = require(`./src/_helpers/arabicToRoman`);
module.exports = function (eleventyConfig) {
eleventyConfig.addShortcode('romanNumeral', romanNumeral);
// bunch of Eleventy config stuff…
};
I created a file named arabicToRoman.js
and put it in my _helpers
directory.
module.exports = function arabicToRoman(number) {
let roman = '';
const romanNumerals = {
M: 1000,
CM: 900,
D: 500,
CD: 400,
C: 100,
XC: 90,
L: 50,
XV: 40,
X: 10,
IX: 9,
V: 5,
IV: 4,
I: 1,
};
let a;
// I will be very surprised if this site is still around in the year 4000
if (number < 1 || number > 3999) {
console.warn('Oooops. Number should be betwixt 1 and 3999');
return null;
} else {
for (let key in romanNumerals) {
a = Math.floor(number / romanNumerals[key]);
if (a >= 0) {
for (let i = 0; i < a; i++) {
roman += key;
}
}
number = number % romanNumerals[key];
}
}
return roman;
};