finding mountains

Benchmark created on


Test runner

Ready to run.

Testing in
TestOps/sec
Mine
function validMountainArray(arr) {
    if(arr.length < 3) return false;

    let forwards = 0;
    for(; forwards < arr.length; forwards++) {
        if(arr[forwards + 1] <= arr[forwards]) break;
    }
    
    let backwards = arr.length - 1;
    for(; backwards >= 0; backwards--) {
        if(arr[backwards - 1] <= arr[backwards]) break;
    }

    return forwards === backwards;
};

[
[2,1],
[1, 2],
[1, 1, 2],
[3, 2, 2],
[0,1,2,3,4,5,6,7,8,9],
[9,8,7,6,5,4,3,2,1,0],
[1, 2, 1],
[1, 2, 3, 2, 1],
[1, 2, 3, 4, 3],
[1, 5, 4, 3, 2],
[0,3,2,1],
[1, 1, 10, 9, 8],
[1, 2, 3, 10, 10],
[1, 2, 3, 3, 2, 1]
].forEach(validMountainArray);
ready
Theirs
function validMountainArray(arr) {
    if (arr.length < 3) return false

    const topIndex = arr.indexOf(arr.reduce((a, b) => Math.max(a, b), -Infinity));

    if (topIndex >= (arr.length - 1) || topIndex <= 0) return false

    for(let i = topIndex; i < arr.length; i++){
        if(i + 1 >= arr.length ) break

        if(!(arr[i] > arr[i + 1])) return false
    }

    for(let i = topIndex; i > 0; i--){
        if(i - 1 < 0) break
        
        if(!(arr[i] > arr[i - 1])) return false
    }

    return true
};

[
[2,1],
[1, 2],
[1, 1, 2],
[3, 2, 2],
[0,1,2,3,4,5,6,7,8,9],
[9,8,7,6,5,4,3,2,1,0],
[1, 2, 1],
[1, 2, 3, 2, 1],
[1, 2, 3, 4, 3],
[1, 5, 4, 3, 2],
[0,3,2,1],
[1, 1, 10, 9, 8],
[1, 2, 3, 10, 10],
[1, 2, 3, 3, 2, 1]
].forEach(validMountainArray);
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.