Skip to content

Instantly share code, notes, and snippets.

@gunzip
Created September 22, 2017 14:46
Show Gist options
  • Save gunzip/f0bf6cef80c3993b6353fa0178c1af4e to your computer and use it in GitHub Desktop.
Save gunzip/f0bf6cef80c3993b6353fa0178c1af4e to your computer and use it in GitHub Desktop.
typescript validation
/**
* A string guaranteed to have a length within the range [L,H)
*/
export type WithinRangeString<L extends number, H extends number> = string &
IWithinRangeStringTag<L, H>;
function validateWithinRangeString<L extends number, H extends number>(
arg: string,
l: L,
h: H
): Option<ReadonlyArray<string>> {
interface IWithinRangeStringObj {
readonly arg: string;
readonly length: number;
}
const validationRules: IValidationRules<IWithinRangeStringObj> = {
arg: [[isString, "not string"]],
length: [[gt(l), "too short"], [lt(h), "too long"]]
};
const validation = validateAll([
{ arg, length: arg.length },
validationRules
]);
if (hasErrors(validation)) {
return option(getErrorStrings(validation));
} else {
return none;
}
}
export function isWithinRangeString<L extends number, H extends number>(
arg: string,
l: L,
h: H
): arg is WithinRangeString<L, H> {
return validateWithinRangeString(arg, l, h).match({
none: always(true),
some: always(false)
});
}
export function toWithinRangeString<L extends number, H extends number>(
arg: string,
l: L,
h: H
): Either<ReadonlyArray<string>, WithinRangeString<L, H>> {
return isWithinRangeString(arg, l, h)
? right(arg)
: left(validateWithinRangeString(arg, l, h).getOrElse([]));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment