I am in need of a solution for ensuring that each instance of my ROOT NODE class always has an ID of 0 upon instantiation.
Furthermore, I want to assign integer IDs sequentially to each child object created from this ROOT NODE. For example, the first child should have an ID of 1, the second child should have an ID of 2, and so on. It's important to note that the child nodes are subclasses of the ROOT NODE.
In my initial implementation, I utilized a generator function that the ROOT NODE referenced for its ID, and then the CHILD NODES accessed the ROOT NODE to obtain their respective IDs. This approach worked as intended:
const skillIdGenerator = (function* () {
let id = 0;
while (true) {
yield id;
id++;
}
})();
class RootNode {
private id: number;
private children: Map<number, Skill>;
constructor() {
this.id = skillIdGenerator.next().value;
this.children = new Map();
}
getId(): number {
return this.id;
}
}
class Node extends RootNode {
private parents: Map<number, RootSkill | Skill>;
constructor(parentSkills: (RootSkill | Skill)[], name: string) {
super();
this.parents = new Map(parentSkills.map((p) => [p.getId(), p]));
}
}
However, this setup does not handle scenarios where there are multiple trees with multiple ROOT NODEs.
I am seeking advice on the most effective way to maintain a generator for all children under each ROOT NODE, while also creating a new generator for each fresh ROOT NODE instantiation.
I experimented with relocating the skillIdGenerator
inside the ROOT NODE class using two different approaches: one as a function returning the next ID, and another as an iterable generator. Unfortunately, both attempts proved unsuccessful.