Coding Problem: Find 1st Bad Version

I. problem

given 500 revisions of programs, write a program that will find and return the FIRST bad revision given a isBad(revision i) function.

II. Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
function isBad( version ){ return version === 0 }

function firstBadVersion( versions ){
if( typeof versions === 'undefined' || versions.length === 0 )
return -1;

let left = 0, right = versions.length-1;
while( left < right ){
let mid = left + Math.floor((right-left)/2)
if( isBad(versions[mid]) ){
right = mid
}else{
left = mid+1
}
}
return versions[left]===0 ? left : -1

}

// Testing 0 1 2 3 4 5 6 should return index: 4
let versions = [1,1,1,1,0,0,0]
console.log(firstBadVersion(versions)) // 4

versions = [1,1,1,1,1,0]
console.log(firstBadVersion(versions)) // 5

versions = [0, 0, 0]
console.log(firstBadVersion(versions)) // 0

versions = [0]
console.log(firstBadVersion(versions)) // 0

versions = [1]
console.log(firstBadVersion(versions)) // -1

versions = [1, 1, 1]
console.log(firstBadVersion(versions)) // -1

versions = []
console.log(firstBadVersion(versions)) // -1

console.log(firstBadVersion()) // -1