Skip to content

Instantly share code, notes, and snippets.

@ryancdotorg
Created July 18, 2014 16:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryancdotorg/1233246214a575842930 to your computer and use it in GitHub Desktop.
Save ryancdotorg/1233246214a575842930 to your computer and use it in GitHub Desktop.
// find the largest value, no more than start, where fn(val) === True
function maximize(start, fn) {
var val = start;
var incr = val;
var best = 0;
var fudge = 1;
do {
incr >>= 1;
if (fn(val)) {
best = Math.max(val, best);
if (val != start) val += incr + 1;
} else {
val -= incr + 1;
}
} while (incr || fudge--);
return best;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment