UNPKG

1.44 kBPlain TextView Raw
1import { StringMap, _truncate } from '@naturalcycles/js-lib'
2
3export interface TableDiffOptions {
4 /**
5 * @default false
6 */
7 logEmpty?: boolean
8
9 /**
10 * @default undefined
11 *
12 * If set - values of each field will be stringified and limited to maxFieldLen.
13 */
14 maxFieldLen?: number
15
16 /**
17 * Title of the A column
18 *
19 * @default `a`
20 */
21 aTitle?: string
22
23 /**
24 * Title of the B column
25 *
26 * @default `b`
27 */
28 bTitle?: string
29}
30
31/**
32 * Compares 2 objects, logs their differences via `console.table`.
33 *
34 * If `logEmpty` is set will explicitly log that fact, otherwise will log nothing.
35 *
36 * Function is located in nodejs-lib (not js-lib), because it's planned to improve in the future and add e.g colors (via chalk).
37 */
38export function tableDiff(
39 a: Record<string, any>,
40 b: Record<string, any>,
41 opt: TableDiffOptions = {},
42): void {
43 const { maxFieldLen, aTitle = 'a', bTitle = 'b' } = opt
44 const diff: StringMap<any> = {}
45
46 if (a && b && a !== b) {
47 new Set([...Object.keys(a), ...Object.keys(b)]).forEach(k => {
48 if (a[k] !== b[k]) {
49 diff[k] = {
50 [aTitle]: maxFieldLen && a[k] ? _truncate(String(a[k]), maxFieldLen) : a[k],
51 [bTitle]: maxFieldLen && b[k] ? _truncate(String(b[k]), maxFieldLen) : b[k],
52 }
53 }
54 })
55 }
56
57 if (Object.keys(diff).length) {
58 console.table(diff)
59 } else if (opt.logEmpty) {
60 console.log('no_difference')
61 }
62}