github.com/hernad/nomad@v1.6.112/ui/app/utils/match-glob.js (about)

     1  /**
     2   * Copyright (c) HashiCorp, Inc.
     3   * SPDX-License-Identifier: MPL-2.0
     4   */
     5  
     6  // @ts-check
     7  
     8  const WILDCARD_GLOB = '*';
     9  
    10  /**
    11   *
    12   * @param {string} pattern
    13   * @param {string} comparable
    14   * @example matchGlob('foo', 'foo') // true
    15   * @example matchGlob('foo', 'bar') // false
    16   * @example matchGlob('foo*', 'footbar') // true
    17   * @example matchGlob('foo*', 'bar') // false
    18   * @example matchGlob('*foo', 'foobar') // false
    19   * @example matchGlob('*foo', 'barfoo') // true
    20   * @example matchGlob('foo*bar', 'footbar') // true
    21   * @returns {boolean}
    22   */
    23  export default function matchGlob(pattern, comparable) {
    24    const parts = pattern?.split(WILDCARD_GLOB);
    25    const hasLeadingGlob = pattern?.startsWith(WILDCARD_GLOB);
    26    const hasTrailingGlob = pattern?.endsWith(WILDCARD_GLOB);
    27    const lastPartOfPattern = parts[parts.length - 1];
    28    const isPatternWithoutGlob = parts.length === 1 && !hasLeadingGlob;
    29  
    30    if (!pattern || !comparable || isPatternWithoutGlob) {
    31      return pattern === comparable;
    32    }
    33  
    34    if (pattern === WILDCARD_GLOB) {
    35      return true;
    36    }
    37  
    38    let subStringToMatchOn = comparable;
    39    for (let i = 0; i < parts.length; i++) {
    40      const part = parts[i];
    41      const idx = subStringToMatchOn?.indexOf(part);
    42      const doesStringIncludeSubPattern = idx > -1;
    43      const doesMatchOnFirstSubpattern = idx === 0;
    44  
    45      if (i === 0 && !hasLeadingGlob && !doesMatchOnFirstSubpattern) {
    46        return false;
    47      }
    48  
    49      if (!doesStringIncludeSubPattern) {
    50        return false;
    51      }
    52  
    53      subStringToMatchOn = subStringToMatchOn.slice(0, idx + comparable.length);
    54    }
    55  
    56    return hasTrailingGlob || comparable.endsWith(lastPartOfPattern);
    57  }