UNPKG

1.41 kBPlain TextView Raw
1import { _truncate, AnyObject } 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(a: AnyObject, b: AnyObject, opt: TableDiffOptions = {}): void {
39 const { maxFieldLen, aTitle = 'a', bTitle = 'b' } = opt
40 const diff: AnyObject = {}
41
42 if (a && b && a !== b) {
43 new Set([...Object.keys(a), ...Object.keys(b)]).forEach(k => {
44 if (a[k] !== b[k]) {
45 diff[k] = {
46 [aTitle]: maxFieldLen && a[k] ? _truncate(String(a[k]), maxFieldLen) : a[k],
47 [bTitle]: maxFieldLen && b[k] ? _truncate(String(b[k]), maxFieldLen) : b[k],
48 }
49 }
50 })
51 }
52
53 if (Object.keys(diff).length) {
54 console.table(diff)
55 } else if (opt.logEmpty) {
56 console.log('no_difference')
57 }
58}