Search code examples
javascriptreactjstypescriptbinary-search

calling a function repeatedly in do while loop


Good day everyone,

So I am learning TypeScript and trying to build an algorithm visualiser for myself to learn. I just hit a block that I just can't get passed. My current way of thinking was that I could assign the returning array to arr and it will just recall itself within the do/while loop, however, I get the following error:

enter image description here

so then my next way of thinking was if there is a way to fix this or perhaps a way I can call the function binarySearch in itself and also be able to return the same variables to handleOnClick.

github repo - link

const handleOnClick = () => {
    let element = 2;
    let arr = [0, 1, 2, 3, 4, 5, 6]
    do {
        var [array, isDone, midPosition] = binarySearch(arr, element);
        // gives [0, 1, 2] false 4
        
        arr = array;
        console.log(array, isDone, midPosition)
    } while (isDone);
}

export function binarySearch (array: number[], element: number) {
    let start = 0;
    let end = array.length - 1;
    let mid = Math.floor((start + end) /2);

    if (element === array[mid]) {
        mid = mid + 1;
        return [array.slice(start, end+1), true, mid]
    }

    if (element < array[mid]) {
        end = mid - 1;
        return [array.slice(start, end+1), false, mid+1];
    } else {
        start = mid + 1;
        return [array.slice(start, end+1), false, mid+1];
    }


}

Solution

  • You need to specify a tuple return type for binarySearch(), otherwise by default TypeScript infers an array of a union type (number | boolean | number[])[] instead.

    function binarySearch (array: number[], element: number): [number[], boolean, number]