JSFiddle - React, Tailwind, and code Playground
by JeffC
JavaScript
// changed all types to var for js
test(2);
function test(b) {
// binary search
// returns the index of b in the array, which in this case is (b - 1)
var s, e, m;
s = 0;
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
e = arr.length - 1;
while (s <= e) {
// added Math.floor since there's no int in js
m = Math.floor((s + e) / 2);
if (arr[m] == b) {
alert(m);
return;
} else if (arr[m] < b) {
s = m + 1;
} else {
e = m - 1;
}
}
alert("Nope");
return;
}