Skip to content

Instantly share code, notes, and snippets.

@liamnewmarch
Last active April 7, 2021 08:13
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 liamnewmarch/da25f36aee886d22ea48115b0f815394 to your computer and use it in GitHub Desktop.
Save liamnewmarch/da25f36aee886d22ea48115b0f815394 to your computer and use it in GitHub Desktop.
Convert numbers to roman numerals.
/**
* RomanNumerals singleton class.
*
* Usage:
*
* RomanNumerals.convert(12); // 'XII'
*/
class RomanNumerals {
static numeralValues = {
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
};
static convert(decimal) {
let string = '';
for (let i in this.numeralValues) {
while (decimal >= this.numeralValues[i]) {
string += i;
decimal -= this.numeralValues[i];
}
}
return string;
}
}
/**
* toRomanNumerals method on the Number prototype.
*
* Usage:
*
* const num = 12;
* num.toRomanNumerals(); // 'XII'
*/
Number.prototype.toRomanNumerals = function() {
return RomanNumerals.convert(this);
};
/**
* <roman-numerals> custom element.
*
* Usage:
*
* <roman-numerals value="12">
* #shadow-root (open)
* "XII"
* </roman-numerals>
*/
customElements.define('roman-numerals', class extends HTMLElement {
static observedAttributes = ['value'];
get value() {
const value = this.getAttribute('value');
return RomanNumerals.convert(value);
}
set value(value) {
this.setAttribute('value', value);
}
constructor() {
super();
this.attachShadow({ mode: 'open' });
this.textNode = document.createTextNode('');
this.shadowRoot.appendChild(this.textNode);
}
attributeChangedCallback(key) {
this.textNode.nodeValue = this.value;
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment