Skip to content

Instantly share code, notes, and snippets.

@havenwood
Created December 31, 2025 19:50
Show Gist options
  • Select an option

  • Save havenwood/f5cde3eda188a5085407e931612ad140 to your computer and use it in GitHub Desktop.

Select an option

Save havenwood/f5cde3eda188a5085407e931612ad140 to your computer and use it in GitHub Desktop.
An example custom HTML element that shows formatted byte sizes
class ByteSize extends HTMLElement {
static observedAttributes = ["si"];
static #binaryUnits = ["B", "KiB", "MiB", "GiB", "TiB"];
static #siUnits = ["B", "KB", "MB", "GB", "TB"];
#initialized = false;
#bytes = 0;
get si() {
return this.hasAttribute("si");
}
set si(value) {
this.toggleAttribute("si", Boolean(value));
}
connectedCallback() {
const text = this.textContent.trim();
if (!text) return;
this.#bytes = Number(text);
this.#initialized = true;
this.#render();
}
attributeChangedCallback() {
if (this.#initialized) this.#render();
}
#render() {
const bytes = this.#bytes;
const formatted = this.#format(bytes);
if (formatted === null) return;
const exact = `${bytes.toLocaleString()} bytes`;
this.textContent = formatted;
this.title = exact;
this.ariaLabel = `${formatted} (${exact})`;
}
#format(bytes) {
if (!Number.isFinite(bytes)) return null;
if (bytes === 0) return "0 B";
const base = this.si ? 1000 : 1024;
const units = this.si ? ByteSize.#siUnits : ByteSize.#binaryUnits;
const abs = Math.abs(bytes);
const exp = Math.min(
Math.floor(Math.log(abs) / Math.log(base)),
units.length - 1
);
const size = bytes / base ** exp;
return `${Number.isInteger(size) ? size : size.toFixed(2)} ${units[exp]}`;
}
}
customElements.define("byte-size", ByteSize);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment