Skip to content

Instantly share code, notes, and snippets.

@Shoghy
Created March 20, 2025 15:38
Show Gist options
  • Save Shoghy/6437075e1da54a8580db6880c757986d to your computer and use it in GitHub Desktop.
Save Shoghy/6437075e1da54a8580db6880c757986d to your computer and use it in GitHub Desktop.
type ValueOfNumber = { valueOf(): number };
abstract class Int<T extends new (value: ValueOfNumber) => InstanceType<T>> {
public abstract get value(): number;
public abstract set value(val: ValueOfNumber);
public abstract valueOf(): number;
private Construct: T;
// eslint-disable-next-line @typescript-eslint/no-unused-vars
public constructor(_: ValueOfNumber) {
this.Construct = this.constructor as T;
}
public add(value: ValueOfNumber) {
return new this.Construct(this.value + value.valueOf());
}
public subtract(value: ValueOfNumber) {
return new this.Construct(this.value - value.valueOf());
}
public divide(value: ValueOfNumber) {
return new this.Construct(this.value / value.valueOf());
}
public multiply(value: ValueOfNumber) {
return new this.Construct(this.value * value.valueOf());
}
public toString(radix: ValueOfNumber = 10) {
return this.value.toString(radix.valueOf());
}
}
export class UInt8 extends Int<typeof UInt8> {
private arr: Uint8Array;
public constructor(value: ValueOfNumber = 0) {
super(value);
this.arr = new Uint8Array(1);
this.arr[0] = value.valueOf();
}
get value(): number {
return this.arr[0];
}
set value(val: ValueOfNumber) {
this.arr[0] = val.valueOf();
}
valueOf() {
return this.arr[0];
}
}
export class Int8 extends Int<typeof Int8> {
private arr: Int8Array;
public constructor(value: ValueOfNumber = 0) {
super(value);
this.arr = new Int8Array(1);
this.arr[0] = value.valueOf();
}
get value(): number {
return this.arr[0];
}
set value(val: ValueOfNumber) {
this.arr[0] = val.valueOf();
}
public valueOf(): number {
return this.arr[0];
}
public override toString(radix: number = 10): string {
let value = this.value;
if (value < 0) {
value = 0xff + value;
}
return value.toString(radix);
}
}
export class UInt16 extends Int<typeof UInt16> {
private arr: Uint16Array;
public constructor(value: ValueOfNumber = 0) {
super(value);
this.arr = new Uint16Array(1);
this.arr[0] = value.valueOf();
}
get value(): number {
return this.arr[0];
}
set value(val: ValueOfNumber) {
this.arr[0] = val.valueOf();
}
valueOf() {
return this.arr[0];
}
}
export class Int16 extends Int<typeof Int16> {
private arr: Int16Array;
public constructor(value: ValueOfNumber = 0) {
super(value);
this.arr = new Int16Array(1);
this.arr[0] = value.valueOf();
}
get value(): number {
return this.arr[0];
}
set value(val: ValueOfNumber) {
this.arr[0] = val.valueOf();
}
public valueOf(): number {
return this.arr[0];
}
public override toString(radix: ValueOfNumber = 10): string {
let value = this.value;
if (value < 0) {
value = 0xffff + value;
}
return value.toString(radix.valueOf());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment