export interface IGuardResult { succeeded : boolean ; message ? : string ; } export interface IGuardArgument { argument : any ; argumentName : string ; } export type GuardArgumentCollection = IGuardArgument [ ] ; export class Guard { public static combine ( guardResults ) { for ( const result of guardResults ) { if ( result . succeeded === false ) { return result ; } } return { succeeded : true } ; } public static againstNullOrUndefined ( argument , argumentName ) { if ( argument === null || argument === undefined ) { return { succeeded : false , message : `${ argumentName } is null or undefined` , } ; } return { succeeded : true } ; } public static againstNullOrUndefinedBulk ( args ) { for ( const arg of args ) { const result = this . againstNullOrUndefined ( arg . argument , arg . argumentName ) ; if ( ! result . succeeded ) return result ; } return { succeeded : true } ; } public static isOneOf ( value , validValues , argumentName ) { let isValid = false ; for ( const validValue of validValues ) { if ( value === validValue ) { isValid = true ; } } if ( isValid ) { return { succeeded : true } ; } return { succeeded : false , message : `${ argumentName } isn't oneOf the correct types in ${ JSON . stringify ( validValues ) }. Got "${ value }".` , } ; } public static inRange ( num , min , max , argumentName ) { const isInRange = num >= min && num <= max ; if ( ! isInRange ) { return { succeeded : false , message : `${ argumentName } is not within range ${ min } to ${ max }.` , } ; } return { succeeded : true } ; } public static allInRange ( numbers , min , max , argumentName ) { let failingResult = { } ; for ( const num of numbers ) { const numIsInRangeResult = this . inRange ( num , min , max , argumentName ) ; if ( ! numIsInRangeResult . succeeded ) { failingResult = numIsInRangeResult ; } } if ( failingResult ) { return { succeeded : false , message : `${ argumentName } is not within the range.` , } ; } return { succeeded : true } ; } }