0

I have the following if-else:

if (entity.length > depot.length) {
    for (var i = 0 ; i < entity.length; i++) {
        promises.push(this.getDataFromREST(security, i));
        console.log(entity, depot)
    }
} else {
    for (var i = 0 ; i < depot.length; i++) {
        promises.push(this.getDataFromREST(security, i));
        console.log(entity, depot)
    }
}

Where entity and depot are arrays, but if they are not holding data they = "NULL".

Basically,for the purposes of this explanation, I want the length of "NULL" to be read as 0, or if entity is an array of length 1+ and depot is a string - the condition entity.length > depot.length is met.

1
  • so depot could be an array or a string? Did I understand that right? Commented Dec 4, 2015 at 11:40

2 Answers 2

4

If both entity and depot can be either "NULL" string or a valid array, you can simply make a check for "NULL", calculate its length once and use one loop:

var loopLength = Math.max(entity === 'NULL' ? 0 : entity.length, 
                           depot === 'NULL' ? 0 : depot.length);

for (var i = 0 ; i < loopLength; i++) {
    promises.push(this.getDataFromREST(security, i));
    console.log(entity, depot)
}

This loop will run only if at least entity or depot is not "NULL" string and a valid non-empty array.

Sign up to request clarification or add additional context in comments.

7 Comments

Ah, excellent. I will try this then I have the time and get back.
This is a cool way of getting the loop length but this will not work in the case that one of them is a string try it out entity="NULL" , depot = [1]. The loopLength should be equal to 1 not 4
@OmarMowafi Oh, now I see, it is a string "NULL". I thought it is a null value. See my update.
@YeldarKurmangaliyev yep that works correctly. My solution also works. I don't understand why I got a down vote :(
@OmarMowafi Probably, because of code duplication. I will give you an upvote if you get rid of it :)
|
2

What you can do is define a function length as follow

function length(s){
   if(s === "NULL") return 0;
   else return s.length;
}

Then write your code as you did but using this function for length

    var entityLength = length(entity);
    var depotLength = length(depot);

    if (entityLength > depotLength) 
       var loopLength = entityLength;
    else
       var loopLength = entityLength;


    for (var i = 0 ; i < loopLength; i++) {
        promises.push(this.getDataFromREST(security, i));
        console.log(entity, depot)
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.