UNPKG

templates-mo

Version:

Templates is a scaffolding framework that makes code generation simple, dynamic, and reusable. Generate files, parts of your app, or whole project structures—without the repetitive copy-pasting

80 lines (79 loc) • 1.96 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Tree = void 0; const queue_1 = require("./queue"); /** * Tree */ // eslint-disable-next-line @typescript-eslint/no-explicit-any class Tree { constructor(value) { this.value = null; if (value) { this.value = value; } this.children = []; this.depth = 0; } addChild(value) { const tree = value; tree.depth = this.depth + 1; this.children.push(tree); return tree; } isRoot() { return this.depth === 0; } hasChildren() { return !!this.children.length; } /** * Breath Methods */ breathFirstEach(cb) { const queue = new queue_1.Queue(); queue.enqueue(this); while (queue.size() > 0) { // if size is not zero then were good const currentTree = queue.dequeue(); if (cb(currentTree) === false) { break; } if (currentTree.hasChildren()) { currentTree.children.forEach((childTree) => { queue.enqueue(childTree); }); } } } breathFirstSelect(cb) { const filtered = []; this.breathFirstEach((tree) => { if (cb(tree)) { filtered.push(tree); } }); return filtered; } /** * Depth Methods */ depthFirstEach(cb) { // change to stack function recurseChildren(tree) { cb(tree); return tree.hasChildren() && tree.children.forEach(recurseChildren); } recurseChildren(this); } depthFirstSelect(cb) { const filtered = []; this.depthFirstEach((tree) => { if (cb(tree)) { filtered.push(tree); } }); return filtered; } } exports.Tree = Tree;