0

I'm challenging myself by doing the different problems in code signal. In the almostIncreasingSequence problem I coded this:

function almostIncreasingSequence(sequence) {
var count = 0;

sequence.forEach((element, i) => {
    if(sequence[i] <= sequence[i-1]){
        count++;
        if(sequence[i] <= sequence[i-2] && sequence[i+1] <= sequence[i-1]){
            return false;
        }
    }
});

return count <= 1;
};

14/17 Answers were correct. But searching for solutions I found that doing the same with a normal for loop it works and I do not know why

function almostIncreasingSequence(sequence) {
    var count = 0;

    for(i=0; i < sequence.length; i++){
        if(sequence[i] <= sequence[i-1]){
            count++;
            if(sequence[i] <= sequence[i-2] && sequence[i+1] <= sequence[i-1]){
                return false;
            }
        }
    }

    return count <= 1;
};
Raúl S
  • 11
  • 1
  • 5
  • You’re more likely looking for [`some`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some) or [`every`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every). – Sebastian Simon Jul 23 '18 at 12:30
  • 1
    Apart from the main issue, please note that you are abusing some pretty harsh implicit coercion: `sequence[i] <= sequence[i-1]` is `sequence[0] <= undefined` for `i === 0`, which is coerced to `sequence[0] <= NaN` which is `false` as desired. However, some otherwise normal logic inversion would already cause unintuitive side effects: `!(sequence[0] > sequence[-1])` will evaluate to `true`. – ASDFGerte Jul 23 '18 at 12:37

0 Answers0