Есть такой цикл:
let children = [];
do {
console.log(tag.create());
children = tag.getChildren();
} while (children.length);
Он на вход получает корневой элемент XMLtag и дальше должен вывести всех его чилдов:
class XMLtag {
private children: XMLtag[] = [];
}
Создание элементов такое:
const tagsTree = new TagsTree();
const orderTag = new XMLtag("order");
orderTag.addAttribute({ name: "id", value: "1" });
const priceTag = new XMLtag("price");
orderTag.addChildren(priceTag);
Почему зацикливается цикл do/while?
Класс целиком:
class XMLtag {
private tagname: string;
private _attributes = new Map<string, string>();
private parent: XMLtag[] = [];
constructor(tagname: string) {
if (!tagname) throw Error("No tag passed!");
this.tagname = tagname;
}
public addAttribute(attribute: { name: string; value: string }) {
if (!attribute) throw Error("No attribute!");
if (!attribute.name) throw "No attribute name!";
if (this._attributes.has(attribute.name)) throw Error("Attribute alread exist!");
this._attributes.set(attribute.name, attribute.value);
}
public create() {
return `<${this.tagname} ${this.attributes}></${this.tagname}>`;
}
public getChildren() {
return this.parent;
}
public addChildren(tag: XMLtag) {
this.parent.push(tag);
}
private get attributes(): string {
let arr: any[] = [];
this._attributes.forEach((value, name) => {
arr.push({ name, value });
});
return arr.map((attribute) => `${attribute.name}="${attribute.value}"`).join(" ");
}
}