这个问题是代码这里的第二个版本。
我在写一个普通的树类。具体来说,每个节点都应该有oen父节点、一定数量的子节点,并保存一个值。
我正在寻找关于如何使这段代码更加地道的一般性建议。我还在寻找关于traverse函数的想法,任何应该出现在普通树类中但不存在的函数,以及简化现有函数的任何方法。
// Code to review
class Node {
constructor(value = 0, children = []) {
this.value = value;
this.children = children;
}
traverse({ preorder, postorder, levelorder }) {
if (levelorder) {
let nodes = [this];
while (nodes.length > 0) {
const current = nodes.shift();
levelorder(current);
nodes = nodes.concat(current.children);
}
}
else {
if (preorder) preorder(this);
this.children.forEach(n => n.traverse({ preorder, postorder }));
if (postorder) postorder(this);
}
return this;
}
clone() {
const copy = n => Object.assign(new Node(), n);
let that = copy(this);
that.traverse({ preorder: n => n.children = n.children.map(copy) });
return that;
}
map(callback) {
let that = this.clone();
that.traverse({ levelorder: n => n.value = callback(n.value) });
return that;
}
reduce(callback, initial) {
let a = initial;
this.traverse({ levelorder: n => a = (n === this && initial === undefined)? n.value: callback(a, n.value) });
return a;
}
filter(callback) {
let that = this.clone();
that.traverse({ levelorder: n => n.children = n.children.filter(m => callback(m.value)) });
return that;
}
every(callback) {
return Boolean(this.reduce((a, b) => a && callback(b), true));
}
some(callback) {
return Boolean(this.reduce((a, b) => a || callback(b), false));
}
find(callback) {
return this.reduce((a, b) => (callback(b)? a.push(b): null, a), []);
}
includes(value) {
return this.some(a => a === value);
}
}
// Testing code
let tree = new Node(0);
let a = new Node(1);
let b = new Node(2);
let c = new Node(3);
let d = new Node(4);
let e = new Node(5);
let f = new Node(6);
tree.children = [a, b, c];
a.children = [d];
d.children = [e, f];
console.log("\nmap", tree.map(a => a + "2"));
console.log("\nreduce", tree.reduce((a, b) => String(a) + String(b)));
console.log("\nfilter", tree.filter(a => a < 3));
console.log("\nevery", tree.every(a => a < 3));
console.log("\nsome", tree.some(a => a < 3))
console.log("\nfind", tree.find(a => a > 2));
console.log("\nincludes", tree.includes(3));发布于 2019-08-26 17:21:49
https://codereview.stackexchange.com/questions/226861
复制相似问题