import * as crypto from "crypto" import * as Leaf from "leaf-ts" type Joint = Type.Topology.Model.Joint export function selfCross(arr: T[], self = false): [T, T][] { let result = [] let offset = 1 if (self) offset = 0 for (let i = 0; i < arr.length; i++) { for (let j = i + offset; j < arr.length; j++) { result.push([arr[i], arr[j]]) } } return result } export function hashStringSet(...args: string[]) { return hashStrings(...args.sort()) } export function hashStrings(...args: string[]) { let spliter = " " return crypto.createHash("md5").update(args.join(spliter)).digest("hex") } export function pickModelByJoint(joints: string[] | string, model: any): any { if (typeof joints == "string") { joints = [joints] } let result = {} for (let joint of joints) { result[joint] = getModelValueByJoint(model, joint) } let map = reconstructObjectMap(result) return map } export function setEqual(t1: T[], t2: T[]): boolean { if (t1.length !== t2.length) return false if (t1 === t2) return false t1 = t1.slice() t2 = t2.slice() for (let i = 0; i < t1.length; i++) { let match = false for (let j = 0; j < t2.length; j++) { if (t1[i] == t2[j]) { match = true t2.splice(j, 1) break } } if (!match) return false } return true } export function getValueByJoint(obj, joint: Joint) { return Leaf.Util.getObjectValue(obj, joint) } export function getModelValueByJoint(model, joint: Joint) { return Leaf.Util.getObjectValue(model, joint.split(".").slice(1).join(".")) } export function fieldPathOfJoint(joint: Joint) { return joint.split(".").slice(1).join(".") } export function flatten(obj: any): { [key: string]: any } { if (!obj) return obj let result = {} let cur = obj for (let key in cur) { let v = cur[key] if (v === null || typeof v === "undefined") { result[key] = v } else if (Array.isArray(v)) { result[key] = v } else if (typeof v == "object") { let child = flatten(v) for (let sub in child) { result[key + sub] = child[sub] } } else { result[key] = v } } return result } export function reconstructObjectMap(map: any) { let result = {} Object.keys(map).forEach(key => { let value = map[key] as string let routes = key.split(".") let node = result let ck: string = null while (ck = routes.shift()) { if (routes.length == 0) { node[ck] = value break } if (typeof node[ck] == "undefined" || node[ck] === null) { node[ck] = {} } node = node[ck] } }) return result } export function makeSet(arr: T[]): T[] { let result = [] for (let item of arr) { if (result.indexOf(item) < 0) { result.push(item) } } return result } export const identity = (_: any) => { return _ } export function getObjectBatchValue(obj: any, path: string) { if (Array.isArray) { return obj.map(child => Leaf.Util.getObjectValue(child, path)) } return Leaf.Util.getObjectValue(obj, path) } export function printLink(link: Type.Topology.Model.Link) { console.log(link.steps.map(item => `${item.joint.from}=>${item.joint.to}`).join("|")) }