Created
September 22, 2017 14:46
-
-
Save gunzip/f0bf6cef80c3993b6353fa0178c1af4e to your computer and use it in GitHub Desktop.
typescript validation
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
/** | |
* 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