Skip to content

Instantly share code, notes, and snippets.

@fsubal
Last active March 25, 2024 14:07
Show Gist options
  • Save fsubal/7d166bb7f1dddcd7a3ac498ad29040fd to your computer and use it in GitHub Desktop.
Save fsubal/7d166bb7f1dddcd7a3ac498ad29040fd to your computer and use it in GitHub Desktop.
export class Byte {
static readonly units = {
terabyte: 2 ** 40,
gigabyte: 2 ** 30,
megabyte: 2 ** 20,
kilobyte: 2 ** 10,
};
private unit = "byte";
private divisor = 1;
private formatter: Intl.NumberFormat;
constructor(readonly value: number) {
for (const [unit, divisor] of Object.entries(Byte.units)) {
if (this.value >= divisor) {
this.unit = unit;
this.divisor = divisor;
break;
}
}
this.formatter = new Intl.NumberFormat("en", {
notation: "compact",
style: "unit",
unit: this.unit,
unitDisplay: "narrow",
});
}
static format(value: number | null): string {
if (value == null) {
return "";
}
return new this(value).format();
}
format() {
return this.formatter.format(this.value / this.divisor);
}
toString() {
return this.format();
}
}
Byte.format(4_194_304);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment