Created
October 2, 2018 11:01
-
-
Save jonniek/edd075c34c3cd85135b689ee005915ec to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function binaryArray(arr) { | |
const array = arr | |
const find = (searchvalue) => { | |
let middle = Math.floor(array.length / 2) | |
let left = 0 | |
let right = array.length | |
while (right >= left) { | |
const value = array[middle] | |
if (value === searchvalue) { | |
return middle | |
} else if (value > searchvalue) { | |
right = middle - 1 | |
} else { | |
left = middle + 1 | |
} | |
middle = Math.floor((left + right) / 2) | |
} | |
return -1 | |
} | |
const add = (addvalue) => { | |
let middle = Math.floor(array.length / 2) | |
let left = 0 | |
let right = array.length | |
while (right >= left) { | |
const value = array[middle] | |
if (value === addvalue) { | |
return false | |
} else if (value > addvalue) { | |
right = middle - 1 | |
} else { | |
left = middle + 1 | |
} | |
middle = Math.floor((left + right) / 2) | |
} | |
array.splice(middle + 1, 0, addvalue) | |
return true | |
} | |
return { | |
find, | |
add, | |
array: function() { return array } | |
} | |
} | |
console.assert(true == false, "Fail check, this test should fail") | |
let BA = binaryArray([1,3,5,7,10]) | |
console.log("Array before inserts: ", BA.array()) | |
console.assert(BA.find(1) == 0, "Index 0 was wrong") | |
console.assert(BA.find(3) == 1, "Index 1 was wrong") | |
console.assert(BA.find(5) == 2, "Index 2 was wrong") | |
console.assert(BA.find(7) == 3, "Index 3 was wrong") | |
console.assert(BA.find(10) == 4,"Index 4 was wrong") | |
console.assert(BA.add(5) == false, "Inserted value that already existed") | |
// insert value 9 | |
console.assert(BA.add(9) == true, "Failed to insert value 9") | |
console.assert(BA.find(9) == 4, "Inserted value 9 at wrong index") | |
// insert value 100 | |
console.assert(BA.add(100) == true, "Failed to insert value 100") | |
console.assert(BA.find(100) == 6, "Inserted value 100 at wrong index") | |
// insert value -10 | |
console.assert(BA.add(-10) == true, "Failed to insert value -10") | |
console.assert(BA.find(-10) == 0, "Inserted value -10 at wrong index") | |
console.log("Array after inserts: ", BA.array()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment