go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/analysis/frontend/ui/src/tools/variant_tools.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  import {
    16    Variant,
    17    Variant_DefEntry,
    18  } from '@/proto/go.chromium.org/luci/analysis/proto/v1/common.pb';
    19  
    20  // variantAsPairs converts a variant (mapping from keys
    21  // to values) into a set of key-value pairs. key-value
    22  // pairs are returned in sorted key order.
    23  export function variantAsPairs(v?: Variant): Variant_DefEntry[] {
    24    const result: Variant_DefEntry[] = [];
    25    if (v === undefined) {
    26      return result;
    27    }
    28    for (const key of Object.keys(v.def)) {
    29      const value = v.def[key] || '';
    30      result.push({ key: key, value: value });
    31    }
    32    result.sort((a, b) => {
    33      return a.key.localeCompare(b.key, 'en');
    34    });
    35    return result;
    36  }
    37  
    38  // unionVariant returns a partial variant which contains
    39  // only the key-value pairs shared by both v1 and v2.
    40  // While it intersects the key-value pairs in both v1 and v2,
    41  // the result is a union in the sense that filtering on the
    42  // partial variant yields a set of varaints that includes
    43  // both v1 and v2.
    44  export function unionVariant(v1?: Variant, v2?: Variant): Variant {
    45    const result: Variant = { def: {} };
    46    if (v1 === undefined || v2 === undefined) {
    47      return result;
    48    }
    49    for (const key of Object.keys(v1.def)) {
    50      // Only keep keys that are both in v1 and v2.
    51      if (!Object.prototype.hasOwnProperty.call(v2.def, key)) {
    52        continue;
    53      }
    54      // Where the value at the key is the same in both v1 and v2.
    55      const value1 = v1.def[key] || '';
    56      const value2 = v2.def[key] || '';
    57      if (value1 == value2) {
    58        result.def[key] = value1;
    59      }
    60    }
    61    return result;
    62  }