Created
February 9, 2015 16:36
-
-
Save greim/2dcedcf3c42ad6b5258f to your computer and use it in GitHub Desktop.
Binary walk function
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
/* | |
* Home in on a number in binary search fashion. | |
* binWalk(2048) === 1024 | |
* binWalk(2048, -1) === 512 | |
* binWalk(2048, -1, -1) === 256 | |
* binWalk(2048, -1, -1, -1) === 128 | |
* binWalk(2048, -1, 1) === 1536 | |
*/ | |
function binWalk(n){ | |
var lo = 0, hi = n, pointer = Math.floor(n/2) | |
for (var i = 1; i<arguments.length; i++){ | |
var arg = arguments[i] | |
if (arg > 0) { | |
lo = pointer | |
} else { | |
hi = pointer | |
} | |
pointer = lo + Math.floor((hi - lo) / 2) | |
} | |
return pointer | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment