traversing nodes
by João Vitor Scheuermann
JavaScript
/*
* NODE CLASS
*/
class Node {
constructor(type, childs) {
this.type = type;
this.childs = childs
this.id = Math.random()
}
}
/*
* TEMPLATES
*/
class Profile {
private __templates = new Object;
constructor(name) {
this.name = name;
}
template(name, fn) {
if (!(name in this.__templates)) {
this.__templates[name] = fn;
} else {
throw new Error(`Template "${name}" is already in use at ${this.name} profile!`);
}
}
getTemplate(name) {
if (name in this.__templates) {
return this.__templates[name];
} else {
try {
return this.__templates["DEFAULT"];
} catch (err) {
try {
return this.__templates["ERROR"];
} catch (err) {
throw new Error(`Template "${name}" isn't declared!`);
}
}
}
}
}
let profile = new Profile('teste');
profile.template('group', (node, childs) => {
console.log(node.type)
return childs(node)
})
profile.template('row', (node, childs) => {
console.log(node.type)
return childs(node)
})
profile.template('col', (node, childs) => {
console.log(node.type)
return childs(node)
})
/*
* TRAVERSE THE NODES
*/
function traverse(profile, node) {
function childs(node) {
for (let child of node.childs) {
traverse(profile, child)
}
}
// GET THE TEMPLATE AND EXECUTE THE CODE
return profile.getTemplate(node.type)(node, childs);
}
/*
* TESTING
*/
let node = new Node('root', [
new Node('group', []),
new Node('group', []),
new Node('group', [
new Node('row', [
new Node('col', [])
])
])
])
traverse(node)