All files / kernel-utils/src merge-disjoint-records.ts

100% Statements 14/14
100% Branches 4/4
100% Functions 2/2
100% Lines 14/14

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33              112x     51x 51x 51x 104x 119x 6x 6x         113x 113x 113x 112x   1x       51x    
/**
 * Create a new record that is the disjoint union of the given records.
 *
 * @param records - The records to union.
 * @returns The disjoint union of the given records.
 * @throws If a key is found in multiple records.
 */
export const mergeDisjointRecords = (
  ...records: Record<PropertyKey, unknown>[]
): Record<PropertyKey, unknown> => {
  const keys = new Map<PropertyKey, number>();
  const out: Record<PropertyKey, unknown> = Object.create(null);
  records.forEach((record, collidingIndex) => {
    for (const key of Reflect.ownKeys(record)) {
      if (keys.has(key)) {
        const originalIndex = keys.get(key);
        throw new Error(
          `Duplicate keys in records: ${String(key)}, found in entries ${originalIndex} and ${collidingIndex}`,
          { cause: { originalIndex, collidingIndex, key } },
        );
      }
      keys.set(key, collidingIndex);
      const desc = Object.getOwnPropertyDescriptor(record, key);
      if (desc) {
        Object.defineProperty(out, key, desc);
      } else {
        out[key] = record[key];
      }
    }
  });
  return out;
};