Created
October 7, 2023 07:44
-
-
Save ryanbaer/8c7216463df4786d4976a9e3665d07be to your computer and use it in GitHub Desktop.
safeParse and ensureParse for numeric strings in Typescript
This file contains 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 Result<T, E extends Error = Error> = { | |
success: true, | |
data: T, | |
} | { | |
success: false, | |
error: E, | |
}; | |
class NumericError extends Error { | |
cause: { input: string }; | |
constructor(input: string, ...args: ConstructorParameters<typeof Error>) { | |
super(...args); | |
this.cause = { input }; | |
} | |
} | |
const Numeric = { | |
parse: (numericString: string, numericType: 'int' | 'float', variant: 'safe' | 'ensure' ): Result<number, NumericError> => { | |
const parseFn = numericType === 'int' ? Number.parseInt : Number.parseFloat; | |
const parsed = parseFn(numericString); | |
if (Number.isNaN(parsed)) { | |
const message = numericType === 'int' | |
? 'NumericParseIntFailure' | |
: 'NumericParseFloatError'; | |
const error = new NumericError(numericString, message); | |
if (variant === 'ensure') { | |
throw error; | |
} | |
return { success: false, error }; | |
} | |
return { success: true, data: parsed }; | |
}, | |
safeParseInt: (numericString: string): Result<number, NumericError> => { | |
return Numeric.parse(numericString, 'int', 'safe'); | |
}, | |
ensureParseInt: (numericString: string) => { | |
return Numeric.parse(numericString, 'int', 'ensure'); | |
}, | |
safeParseFloat: (numericString: string): Result<number, NumericError> => { | |
return Numeric.parse(numericString, 'float', 'safe'); | |
}, | |
ensureParseFloat: (numericString: string) => { | |
return Numeric.parse(numericString, 'float', 'ensure'); | |
}, | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment