flebas
flebas

Reputation: 99

VBScript loop advice

sqlRows = rst.GetRows()
i = 0

For Each element In sqlRows
    If i > 0 And i < sizeOfState + 1 Then 
        SmartTags("visu_state_on")(i - 1) = element
    ElseIf i > sizeOfState And i < 2 * sizeOfState + 1 Then
        SmartTags("visu_state_off")(i - sizeOfState - 1) = element
    ElseIf i > (2 * sizeOfState ) And i < 2 * sizeOfState + sizeOfMeasurement + 1 Then
        SmartTags("visu_limits_right")(i - (2 * sizeOfState - 1)) = element
    ElseIf i > 2 * sizeOfState + sizeOfMeasurement And i < 2 * (sizeOfStanja + sizeOfMeasurement ) + 1 Then
        SmartTags("visu_limits_left")(i - (2 * sizeOfState + sizeOfMeasurement )) = element
    End If

    i = i + 1
Next

With code above I'm looping through array sqlRows and with variable i I'm filling other four arrays with data from sqlRows.

This solution works but I'm wondering is there more elegant way to achieve the same.

and variables sizeOfState and sizeOfMeasurement are just there that I can calculate indexes for these four arrays.

Upvotes: 0

Views: 118

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200573

For one thing you can remove the first clause from each of your conditions, because they will always be true

  • i starts with the value 0 and is always incremented, so the value will never be less than zero.
  • If a value is not less than n + 1 (condition in previous ElseIf) then it's guaranteed to be greater than n.

Also, VBScript does have a <= comparison operator, so it's better to compare i <= n rather than i < n + 1.

I would also recommend calculating values that won't change inside the loop just once outside the loop. Re-calculating them with each loop cycle is a waste of resources.

Adding an Else branch to handle values greater than 2 * (sizeOfStanja + sizeOfMeasurement) might be a good idea too.

sqlRows = rst.GetRows()
i = 0

ref1 = 2 * sizeOfState
ref2 = ref1 + sizeOfMeasurement
ref3 = 2 * (sizeOfStanja + sizeOfMeasurement)

For Each element In sqlRows
  If i <= sizeOfState Then 
    SmartTags("visu_state_on")(i - 1) = element
  ElseIf i <= ref1 Then
    SmartTags("visu_state_off")(i - sizeOfState - 1) = element
  ElseIf i <= ref2 Then
    SmartTags("visu_limits_right")(i - ref1 + 1) = element
  ElseIf i <= ref3 Then
    SmartTags("visu_limits_left")(i - ref2) = element
  Else
    'handle i > ref3 here
  End If

  i = i + 1
Next

Upvotes: 2

Related Questions