Created
September 22, 2017 14:51
-
-
Save gunzip/6ff5c179dfb26c89b08c3e45edd32fc9 to your computer and use it in GitHub Desktop.
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>> { | |
const validation = validateAll([ | |
{ arg, length: arg.length }, | |
{ | |
arg: [[isString, "not string"]], | |
length: [[gt(l), "too short"], [lt(h), "too long"]] | |
} | |
]); | |
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