Skip to content

Instantly share code, notes, and snippets.

@kurorido
Created October 13, 2015 09:38
Show Gist options
  • Select an option

  • Save kurorido/962e351e4a9108906fce to your computer and use it in GitHub Desktop.

Select an option

Save kurorido/962e351e4a9108906fce to your computer and use it in GitHub Desktop.
var getClosestValues = function(a, x) {
var lo = -1, hi = a.length;
while (hi - lo > 1) {
var mid = Math.round((lo + hi)/2);
if (a[mid] <= x) {
lo = mid;
} else {
hi = mid;
}
}
if (a[lo] == x) hi = lo;
return [a[lo], a[hi]];
}
var getLyricByTimestamp = function(a, x) {
var lo = -1, hi = a.length;
if(x >= a[hi-1]["timestamp"]) {
return [hi, hi]
}
if(x <= a[0]["timestamp"]) {
return [0, 0];
}
while (hi - lo > 1) {
var mid = Math.round((lo + hi)/2);
if (a[mid]["timestamp"] <= x) {
lo = mid;
} else {
hi = mid;
}
}
if (a[lo]["timestamp"] == x) hi = lo;
return hi;
}
var getClosestIndex = function(a, x) {
var lo = -1, hi = a.length;
if(x >= a[hi-1]) {
return [hi, hi]
}
if(x <= a[0]) {
return [0, 0];
}
while (hi - lo > 1) {
var mid = Math.round((lo + hi)/2);
if (a[mid] <= x) {
lo = mid;
} else {
hi = mid;
}
}
if (a[lo] == x) hi = lo;
return [lo, hi];
}
var arr = [1.2, 2.4, 3.6, 4.8];
console.log(getClosestIndex(arr, -2));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment