Created
April 6, 2025 09:59
-
-
Save mt-shihab26/5a95cbb8420a6b0e67eec4c2ada641d9 to your computer and use it in GitHub Desktop.
Builder design pattern with #TypeScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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