Max function in ASP

The VBScript (at least its ASP dialect) is not very strong in math functions. For example, the simple Max function is missing. It's not hard to write, though:
Function Max(A,B)
  Max = A : If B > A Then Max = B
End Function
Things get a bit more complex if you want to take in account the NULL values (assuming non-NULL is always greater than NULL):
Function Max(A,B)
  Max = A : If IsNull(B) Then Exit Function
  If B > A Or IsNull(A) Then Max = B
End Function
However, I prefer the multi-value function that can take as many arguments as you like (unfortunately in an array, as VBScript functions can't take variable number of arguments):
Function MaxArray(A)
  Dim I
  MaxArray = A(LBound(A))
  For I = LBound(A) + 1 To UBound(A)
    If A(I) > MaxArray Or IsNull(MaxArray) Then MaxArray = A(I)
End Function

The code uses a VBScript quirk: function name without parenthesis when used within the function refers to the current function's value, not a recursive call

To call the MaxArray function, you don't have to construct an array beforehand, you can also use the array VBScript function, for example:

mxv = MaxArray(array(A,B,C,D))

No comments:

Post a Comment