go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/milo/ui/src/generic_libs/tools/string_utils/string_utils.ts (about)

     1  // Copyright 2024 The LUCI Authors.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  /**
    16   * Get the longest common prefix of the strings. This is not optimized to
    17   * handle large datasets.
    18   */
    19  export function getLongestCommonPrefix(strings: readonly string[]): string {
    20    if (!strings.length) {
    21      return '';
    22    }
    23  
    24    const baseStr = strings[0];
    25    let commonPrefixLength = baseStr.length;
    26    for (let i = 1; i < strings.length; ++i) {
    27      const compareStr = strings[i];
    28      for (let j = 0; j < commonPrefixLength; ++j) {
    29        if (baseStr[j] !== compareStr[j]) {
    30          commonPrefixLength = j;
    31          break;
    32        }
    33      }
    34    }
    35    return baseStr.slice(0, commonPrefixLength);
    36  }
    37  
    38  /**
    39   * Format number with a cap. If the number is greater than `cap`, display
    40   * `${cap}+` instead. This is useful when displaying a large number in limited
    41   * space.
    42   */
    43  export function formatNum(num: number, hasMore: boolean, cap?: number) {
    44    if (cap && num > cap) {
    45      return `${cap}+`;
    46    } else if (hasMore) {
    47      return `${num}+`;
    48    }
    49    return `${num}`;
    50  }