Created
October 5, 2022 04:58
-
-
Save Segmentational/7870180758d62402a4715a2364eca176 to your computer and use it in GitHub Desktop.
Recursive Parent-Child Walker
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Cryptography from "crypto"; | |
/*** | |
* @example | |
* void (async () => { | |
* const parent = new Abstract("root"); | |
* | |
* const child = new Abstract("child-1", parent); | |
* | |
* new Abstract("child-3", child); | |
* | |
* new Abstract("child-2", parent); | |
* | |
* console.log(parent.walk()); | |
* | |
* for (const walker of parent.walk()) { | |
* console.log(walker.json); | |
* } | |
* })(); | |
*/ | |
class Abstract { | |
private id: string; | |
private uuid = () => Cryptography.randomUUID({ disableEntropyCache: true }); | |
constructor(readonly name: string, readonly parent: Abstract | null = null, readonly children: Abstract[] | null = null) { | |
this.id = this.uuid(); | |
(name) && Reflect.set(this, "name", name); | |
(parent) && Reflect.set(this, "parent", parent.id); | |
(parent) && ((parent.children) && parent.children.push(this) || Reflect.set(parent, "children", [ this ])); | |
(this.name) && Reflect.set(this, Symbol.for(this.name), this); | |
} | |
get json() { | |
return JSON.stringify(this, null, 4); | |
} | |
walk() { | |
if (!(Reflect.get(this.walk, "children"))) { | |
Reflect.set(this.walk, "children", []); | |
} | |
const children: Abstract[] = Reflect.get(this.walk, "children"); | |
(this.children) && (() => { | |
for (const child of this.children) { | |
children.push(child); | |
child.walk(); | |
} | |
Reflect.set(this.walk, "children", children); | |
})(); | |
const data = Array.from([this, ... Reflect.get(this.walk, "children") as Abstract[]]); | |
Reflect.set(this.walk, "children", null); | |
return data; | |
} | |
} | |
void (async () => { | |
const parent = new Abstract("root"); | |
const child = new Abstract("child-1", parent); | |
new Abstract("child-3", child); | |
new Abstract("child-2", parent); | |
console.log(parent.walk()); | |
for (const walker of parent.walk()) { | |
console.log(walker.json); | |
} | |
console.log(parent.walk()); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment