File tree Expand file tree Collapse file tree
lib/source-code/token-store Expand file tree Collapse file tree Original file line number Diff line number Diff line change 44 */
55"use strict" ;
66
7- //------------------------------------------------------------------------------
8- // Helpers
9- //------------------------------------------------------------------------------
10-
11- /**
12- * Gets `token.range[0]` from the given token.
13- * @param {Node|Token|Comment } token The token to get.
14- * @returns {number } The start location.
15- * @private
16- */
17- function getStartLocation ( token ) {
18- return token . range [ 0 ] ;
19- }
20-
217//------------------------------------------------------------------------------
228// Exports
239//------------------------------------------------------------------------------
@@ -30,9 +16,28 @@ function getStartLocation(token) {
3016 * @returns {number } The found index or `tokens.length`.
3117 */
3218exports . search = function search ( tokens , location ) {
33- const index = tokens . findIndex ( el => location <= getStartLocation ( el ) ) ;
19+ for ( let minIndex = 0 , maxIndex = tokens . length - 1 ; minIndex <= maxIndex ; ) {
3420
35- return index === - 1 ? tokens . length : index ;
21+ /*
22+ * Calculate the index in the middle between minIndex and maxIndex.
23+ * `| 0` is used to round a fractional value down to the nearest integer: this is similar to
24+ * using `Math.trunc()` or `Math.floor()`, but performance tests have shown this method to
25+ * be faster.
26+ */
27+ const index = ( minIndex + maxIndex ) / 2 | 0 ;
28+ const token = tokens [ index ] ;
29+ const tokenStartLocation = token . range [ 0 ] ;
30+
31+ if ( location <= tokenStartLocation ) {
32+ if ( index === minIndex ) {
33+ return index ;
34+ }
35+ maxIndex = index ;
36+ } else {
37+ minIndex = index + 1 ;
38+ }
39+ }
40+ return tokens . length ;
3641} ;
3742
3843/**
You can’t perform that action at this time.
0 commit comments