tor-browser

The Tor Browser
git clone https://git.dasho.dev/tor-browser.git
Log | Files | Refs | README | LICENSE

get-matches.js (1402B)


      1 /* This Source Code Form is subject to the terms of the Mozilla Public
      2 * License, v. 2.0. If a copy of the MPL was not distributed with this
      3 * file, You can obtain one at <http://mozilla.org/MPL/2.0/>. */
      4 
      5 import assert from "../../utils/assert";
      6 import buildQuery from "../../utils/build-query";
      7 
      8 export default function getMatches(query, text, options) {
      9  if (!query || !text || !options) {
     10    return [];
     11  }
     12  const regexQuery = buildQuery(query, options, {
     13    isGlobal: true,
     14  });
     15  const matchedLocations = [];
     16  const lines = text.split("\n");
     17  for (let i = 0; i < lines.length; i++) {
     18    let singleMatch;
     19    const line = lines[i];
     20    while ((singleMatch = regexQuery.exec(line)) !== null) {
     21      // Flow doesn't understand the test above.
     22      if (!singleMatch) {
     23        throw new Error("no singleMatch");
     24      }
     25 
     26      matchedLocations.push({
     27        line: i,
     28        ch: singleMatch.index,
     29        match: singleMatch[0],
     30      });
     31 
     32      // When the match is an empty string the regexQuery.lastIndex will not
     33      // change resulting in an infinite loop so we need to check for this and
     34      // increment it manually in that case.  See issue #7023
     35      if (singleMatch[0] === "") {
     36        assert(
     37          !regexQuery.unicode,
     38          "lastIndex++ can cause issues in unicode mode"
     39        );
     40        regexQuery.lastIndex++;
     41      }
     42    }
     43  }
     44  return matchedLocations;
     45 }