import { IBinaryTree } from '../../common/types'; import stringWidth from 'string-width'; export function isPlainObj(data: any): data is object { return Object.prototype.toString.call(data) === '[object Object]'; } export function array1dTo2d(data: T[], width: number = 10): T[][] { const r = []; const il = Math.ceil(data.length / width); let i = 0; while (i < il) { r.push(data.slice(i * width, (i + 1) * width)); i++; } return r; } export function array1dToBinayTree(data: T[]): IBinaryTree | null { const L = data.length; if (L === 0) return null; const root = { val: data[0], left: null, right: null }; let list: IBinaryTree[] = [root]; let i = 1; while (list.length) { const newList: IBinaryTree[] = []; list.forEach(node => { node.left = i < L && data[i] !== null ? { val: data[i], left: null, right: null } : null; i++; node.right = i < L && data[i] !== null ? { val: data[i], left: null, right: null } : null; i++; if (node.left) newList.push(node.left); if (node.right) newList.push(node.right); }); list = newList; } return root; } export function arrayHeapToBinaryTree(data: T[]): IBinaryTree | null { const L = data.length; const f = (i: number): IBinaryTree | null => { if (i < L) { return { val: data[i], left: f(i * 2), right: f(i * 2 + 1), }; } else { return null; } }; return f(1); } export function flipArray2D(data: T[][]): T[][] { const r: T[][] = []; const H = data.length; for (let h = 0; h < H; ++h) { const row = data[h]; for (let w = 0, l = row.length; w < l; ++w) { if (r[w] === undefined) { r[w] = []; } r[w][h] = row[w]; } } return r; } export const getStringWidth = stringWidth;