Skip to content

Instantly share code, notes, and snippets.

@mt-shihab26
Created April 6, 2025 09:59
Show Gist options
  • Select an option

  • Save mt-shihab26/5a95cbb8420a6b0e67eec4c2ada641d9 to your computer and use it in GitHub Desktop.

Select an option

Save mt-shihab26/5a95cbb8420a6b0e67eec4c2ada641d9 to your computer and use it in GitHub Desktop.
Builder design pattern with #TypeScript
type TInitValue = string | number | null | undefined;
class Money {
private value: number | null;
constructor(initValue: TInitValue) {
if (!initValue) {
this.value = null;
return;
}
switch (typeof initValue) {
case 'string':
const cleanedValue = initValue.replace(/[^0-9.-]/g, '');
const parsedValue = parseFloat(cleanedValue);
this.value = isNaN(parsedValue) ? null : parsedValue || null;
return;
case 'number':
this.value = initValue;
return;
}
}
cents = (): Money => new Money(this.value ? Math.round(this.value * 100) : null);
dollars = (): Money => new Money(this.value ? this.value / 100 : null);
number = (): number | null => this.value || null;
string = (): string | null => (this.value ? String(this.value) : null);
}
export const money = (value: TInitValue) => {
return new Money(value);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment