Search code examples
javascriptfor-loopif-statementcoffeescript

if statement only executing on index 2 of for loop


I've this for loop in my coffeescript:

compareVersions = (current, minimum) ->
    console.log('current ', current)
    console.log('minimum ', minimum)
    current_parts = current.split '.'
    minimum_parts = minimum.split '.'
    for partIndex in [0..Math.min(current_parts.length, minimum_parts.length)]
       console.log('partIndex ', partIndex)
       if (+current_parts[partIndex] || 0) < (+minimum_parts[partIndex] || 0)
         console.log('current_parts.length1 ', current_parts[partIndex])
         console.log('minimum_parts.length1 ', minimum_parts[partIndex])
         return false
    console.log('PC current_parts.length2 ', current_parts[partIndex])
    console.log('PC minimum_parts.length2 ', minimum_parts[partIndex])
    true

It's designed to compare software versions and return false if the current version is lower than the minimum version.

I added the console.log's to show what's happening.

This is the output I get. In this case the current version is higner than the minimum but the if statement only executes on index 2 which in this case has a lower number for the current than for the minimum.

current  3.4.1.35
minimum  3.3.3
partIndex  0
partIndex  1
partIndex  2
current_parts.length1  1
minimum_parts.length1  3

The if statement should execute for each iteration of the for loop. What is wrong here that is preventing this?


Solution

  • The if statement is executing in each iteration of the for loop, but the current_parts.length1 and minimum_parts.length1 are printed when the if statement is true.

    The execution of your if statement would be:

    3 < 3 false
    4 < 3 false
    1 < 3 true
        print current_parts.length1
        print minimum_parts.length1
    

    If you want to show current_parts.length1 and minimum_parts.length1, put them outside of the if statement so you will see the values when the if statement is going to execute.