import chalk from 'chalk'; import { IBaseType, arrayHeapToBinaryTree, array1dToBinayTree, array1dTo2d, isPlainObj, getStringWidth as sw, } from '../../../'; import { ILogData, ILogOptions, ICharMatrix } from '../type'; import { parseTable } from './table'; import { parseBinaryTree } from './btree'; import { parseTree } from './tree'; export function parse(data: ILogData, options: ILogOptions = {}): ICharMatrix { const t = typeof data; if (data !== null && t === 'object') { if (data instanceof Set) { // Set return parse(Array.from(data), options); } else if (data instanceof Map) { // Map const table = Array.from(data.entries()); table.unshift(['', '']); return parse(table, { ...options, showColHead: false, showRowHead: false, }); } else if (Array.isArray(data)) { if (data.length === 0) { return { v: [''], w: 13, h: 1, }; } else if (Array.isArray(data[0])) { // Array2D return parseTable(data as ILogData[][], options); } else if (options.isHeap) { // 用数组表示的堆 return parseBinaryTree(arrayHeapToBinaryTree(data as IBaseType[])!, options); } else if (options.isTree) { // 用数组表示的树 return parseTree(array1dToBinayTree(data) as any, options); } else { // Array1D return parse(array1dTo2d(data), options); } } else if (isPlainObj(data)) { if (data.hasOwnProperty('next')) { // LinkList const r: ILogData[] = []; let d: any = data; while (d) { r.push(d.val); d = d.next; } return parse(d, options); } else if (data.hasOwnProperty('left')) { // Binary Tree return parseBinaryTree(data as any, options); } else if (data.hasOwnProperty('childs')) { // Tree return parseTree(data as any, options); } else { // Plain Obj const table = Object.entries(data); return parse(table, { ...options, showColHead: true, showRowHead: false, cols: [{ key: '' }, { key: '' }], }); } } } const v = data + ''; const c = t === 'string' ? 'green' : t === 'undefined' || data === null ? 'grey' : 'yellow'; return { v: [chalk[c](v)], w: sw(v), h: 1 }; }