Skip to content

Commit

Permalink
perf: Skip binary search when timestamp is after last transition
Browse files Browse the repository at this point in the history
Many zones don't have any future transitions (i.e. all their transitions are in
the past, and they don't have any planned DST changes). For these zones,
looping over the `untils` array is pointless for any "now-ish" timestamp.
If the timestamp being checked is after the last `until`, we can skip the binary
search completely.
  • Loading branch information
gilmoreorless committed May 21, 2023
1 parent ccaf698 commit 287820a
Showing 1 changed file with 7 additions and 4 deletions.
11 changes: 7 additions & 4 deletions moment-timezone.js
Original file line number Diff line number Diff line change
Expand Up @@ -150,16 +150,19 @@
}
}

function closest(num, arr) {
function closest (num, arr) {
var len = arr.length;
if (num < arr[0]) {
return 0;
} else if (num >= arr[arr.length-1]) {
} else if (len > 1 && arr[len - 1] === Infinity && num >= arr[len - 2]) {
return len - 1;
} else if (num >= arr[len - 1]) {
return -1;
}

var mid;
var lo = 0;
var hi = arr.length - 1;
var hi = len - 1;
while (hi - lo > 1) {
mid = Math.floor((lo + hi) / 2);
if (arr[mid] <= num) {
Expand All @@ -185,7 +188,7 @@
untils = this.untils,
i;

i = closest(target,untils);
i = closest(target, untils);
if (i >= 0) {
return i;
}
Expand Down

0 comments on commit 287820a

Please sign in to comment.