Binary search

in #itayesterday

export function find(haystack: number[], needle: number, counter: number = 0): number | never {

const maxNumber = Math.max(...haystack);

let middle = Math.floor(haystack.length/2);

if(needle === 0 || haystack.length === 0 ||(haystack.length !==0 && maxNumber<needle)

|| !haystack.includes(needle)) throw new Error("Value not in array");

if(haystack.length === 1) return counter;

if(haystack[haystack.length-1] === needle) return counter + haystack.length-1;

if(haystack[middle] === needle) return counter + middle;

else if(haystack[middle] > needle) return find(haystack.slice(0, middle), needle, counter);

else return find(haystack.slice(middle+1, haystack.length), needle, counter+middle+1);

}