cs_almostSequential

js tech screen

by David McClelland

JavaScript

function solution(arr) {
    if(arr.length == 2) {
        console.log('too few values');
        return true;
    }
    
    let uvPos1 = checkAscending(arr);
    let uvPos2 = uvPos1 + 1;

    // clone arr, remove uvPos1 value and compare to sorted clone of it
    let arr2 = [...arr];
    arr2.splice(uvPos1, 1);
    let sortedArr2 = [... new Set(arr2)];
    sortedArr2.sort(function(a, b){return a-b});
    // compare arrs
    if(arr2.join(",") == sortedArr2.join(",")) {
        console.log('matching uvs');
        return true;
    }
 
    // repeat with uvPos2
    // clone arr, remove uvPos1 value and compare to sorted clone of it
    let arr3 = [...arr];
    arr3.splice(uvPos2, 1);
    let sortedArr3 = [... new Set(arr3)];
    sortedArr3.sort(function(a, b){return a-b});
    // compare arrs
    if(arr3.join(",") == sortedArr3.join(",")) {
        console.log('matching uvs');
        return true;
    }

    return false;
};

function checkAscending(arr) {
    let result = -1;
        let newArr = arr.map((item, index) => {
        // if there is one more item in arr after current index, compare them for order
        if (arr[index + 1]){
            let unexpected = item >= arr[index + 1] ? true : false;
            if (unexpected) {
                result = index;
            }
        }
    });
    return result;
}

console.log(solution([1,2,1,2]))