Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: change Timetree to class statement #182

Merged
merged 4 commits into from
Mar 21, 2022
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
chore: class changes
xtx1130 committed Mar 21, 2022

Verified

This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
commit 1334b1db52733a79adc43aea2cc71e49692ba6de
109 changes: 109 additions & 0 deletions time-tree-class.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
'use strict'

const archy = require('archy')

class TimeTree {
constructor () {
this.root = null
this.tableId = new Map()
this.tableLabel = new Map()
}

trackNode (node) {
this.tableId.set(node.id, node)
if (this.tableLabel.has(node.label)) {
this.tableLabel.get(node.label).push(node)
} else {
this.tableLabel.set(node.label, [node])
}
}

untrackNode (node) {
this.tableId.delete(node.id)

const labelNode = this.tableLabel.get(node.label)
if (labelNode.id) {
this.tableLabel.delete(node.label)
return
}
labelNode.pop()

if (labelNode.length === 0) {
this.tableLabel.delete(node.label)
}
}

getParent (parent) {
if (parent === null) {
return this.root
}

const parentNode = this.tableLabel.get(parent)
if (parentNode.id) {
return parentNode
}
return parentNode[parentNode.length - 1]
}

getNode (nodeId) {
return this.tableId.get(nodeId)
}

add (parent, child, start) {
const isRoot = parent === null
if (isRoot) {
this.root = {
id: 'root',
label: child,
start,
nodes: []
}
this.trackNode(this.root)
return this.root.id
}

const parentNode = this.getParent(parent)
const nodeId = `${child}-${Math.random()}`
const childNode = {
id: nodeId,
parent,
start,
label: child,
nodes: []
}
parentNode.nodes.push(childNode)
this.trackNode(childNode)
return nodeId
}

start (parent, child, start = Date.now()) {
return this.add(parent, child, start)
}

stop (nodeId, stop = Date.now()) {
const node = this.getNode(nodeId)
if (node) {
node.stop = stop
node.diff = (node.stop - node.start) || 0
this.untrackNode(node)
}
}

toJSON () {
return Object.assign({}, this.root)
}

prittyPrint () {
const decorateText = (node) => {
node.label = `${node.label} ${node.diff} ms`
if (node.nodes.length > 0) {
node.nodes = node.nodes.map(_ => decorateText(_))
}
return node
}
const out = decorateText(this.toJSON())
return archy(out)
}
}

module.exports = TimeTree