Skip to content

Instantly share code, notes, and snippets.

@ryanbaer
Created October 7, 2023 07:44
Show Gist options
  • Save ryanbaer/8c7216463df4786d4976a9e3665d07be to your computer and use it in GitHub Desktop.
Save ryanbaer/8c7216463df4786d4976a9e3665d07be to your computer and use it in GitHub Desktop.
safeParse and ensureParse for numeric strings in Typescript
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