All files / src keys-of-objects.ts

73.68% Statements 14/19
40% Branches 2/5
100% Functions 3/3
68.75% Lines 11/16

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    22x 4152x               22x 21x     21x     21x 21x 4124x 4124x           21x     22x  
/** @returns `true` if boths string arrays are the same. */
export const same =
  (xs: string[], ys: string[]): boolean =>
    xs.length === ys.length && xs.every((x, i) => x === ys[i])
 
/**
 * @returns keys of all objects in array
 * @throws if objects have different keys.
 * @throws if an array is empty.
 */
export const keysOfObjects =
  (objects: readonly Record<string, unknown>[]): string[] => {
    Iif (!Array.isArray(objects)) {
      throw new TypeError(`Expected array, got ${objects}.`)
    }
    Iif (objects.length === 0) {
      throw new TypeError('Expected non empty array.')
    }
    const keys = Object.keys(objects[0]).sort()
    for (let i = 1; i < objects.length; i++) {
      const keys_ = Object.keys(objects[i]).sort()
      Iif (!same(keys, keys_)) {
        throw new TypeError(`Expected same keys on all objects, got ${keys} and ${keys_} at ${i} index.`)
      }
    }
 
    // Return naturally ordered keys.
    return Object.keys(objects[0])
  }
 
export default keysOfObjects