0
if (firstPositionCpc && (firstPosition > 0 && firstPositionCpc <= maxCPC)) {
    var newCPC = firstPositionCpc;
} else if (topOfPageCpc && (topOfPageCpc > 0 && topOfPageCpc <= maxCPC)) {
    var newCPC = topOfPageCpc;
} else if (firstPageCpc && (firstPageCpc > 0 && firstPageCpc <= maxCPC )) {
    var newCPC = firstPageCpc;
} else {
    var newCPC = minCPC;
}

Here is some wrong scenario

KeywordIdReport :197857118477
campaignName :BP 2015 QC (FR)
maxCPC : 3.00
OldCPC :0.46
firstPositionCpc : --
topOfPageCpc : 0.46
firstPageCpc : 0.05
NewCPC : --

Here NewCPC needs to be a number. Hence, firstPositionCpc, topOfPageCpc and firstPageCpc need to exist and be a number.

KeywordIdReport :97483945
campaignName :BP 2015 QC (FR)
maxCPC: 3.00
OldCPC :1.96
firstPositionCpc : 4.28
topOfPageCpc : 1.68
firstPageCpc : 0.85
NewCPC : 4.28

Here NewCPC needs to be lower or equal to maxCPC. Normally, the answer should be 1.68 instead of 4.28 for NewCPC.

How could I fix the chain of if statement so that it will fix the wrong scenarios?

UPDATE

Now after improvement, how could I say that the type of firstPositionCpc, topOfPageCpc and firstPageCpc exist and need to be a number?

Dave
  • 85
  • 10
  • I don't know if it's the whole problem, but JavaScript (like C, C++, Java, C#, and other languages in the B syntax tradition) doesn't support `0 < firstPositionCpc <= maxCPC` comparisons. If that's meant to be `firstPositionCpc > 0 && firstPositionCpc <= maxCPC`, you have to write that explicitly. – T.J. Crowder Nov 13 '17 at 14:00
  • Possible duplicate of [Validate that a string is a positive integer](https://stackoverflow.com/questions/10834796/validate-that-a-string-is-a-positive-integer) – Ruud Helderman Nov 13 '17 at 14:25

1 Answers1

1

Hence, firstPositionCpc, topOfPageCpc and firstPageCpc need to exist and be a number.

The above doesn't really make sense given that you have 3 comparisons, so my answer will lean on the assumption that you want firstPosition > 0.

So I need to check if a value type is number and if that number is in some bound so taking your first if statement:

if (firstPositionCpc && (firstPosition > 0 && firstPositionCpc <= maxCPC)) {
    var newCPC = firstPositionCpc;
}

I would change it to the following:

if(typeof(firstPositionCpc) == 'number' && firstPositionCpc <= maxCPC && firstPosition > 0){....}

typeof() reads the type of the parameter and returns a string indicating the value.

See here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof

Callat
  • 2,928
  • 5
  • 30
  • 47