tom*_*tom 4 javascript recursion json typescript
我有一个类似 JSON 的 JS 对象层次结构,格式如下:
[
{
subs: [ ...other objects... ]
},
...other objects...
]
Run Code Online (Sandbox Code Playgroud)
我编写了一个返回此类层次结构的级别数的方法:
/* Returns the depth of the tree. */
public getDepth(): number {
function f(obj: object): number {
let depth = 0;
if (obj['subs'].length > 0) {
obj['subs'].forEach((s: object) => {
const tempDepth = f(s);
if (tempDepth > depth) depth = tempDepth;
});
}
return depth + 1;
}
if (this.tree.length > 0)
return Math.max(...this.tree.map((s: object) => f(s)));
else return 0;
}
Run Code Online (Sandbox Code Playgroud)
它有效,但太复杂了。然后,我发现了这个更干净的代码:/sf/answers/1125318351/
唯一的区别是我没有一个基础对象,而是一组对象作为根。我怎样才能简化代码以节省额外的 if 和迭代?
示例数据:
const data1 = []; // depth: 0
const data2 = [{}, {}, {}]; // depth: 1
const data3 = [{}, // depth: 5
{
"subs": [{
"subs": [{
"subs": [{}]
}, {
"subs": [{
"subs": [{}]
}]
}]
}, {
"subs": [{
"subs": [{}]
}]
}]
},
{}
];
Run Code Online (Sandbox Code Playgroud)
您可以绘制每个孩子的深度并取其最大值。
function getDepth(array) {
return 1 + Math.max(0, ...array.map(({ subs = [] }) => getDepth(subs)));
}
const
data1 = [],
data2 = [{}, {}, {}],
data3 = [{}, { subs: [{ subs: [{ subs: [{}] }, { subs: [{ subs: [{}] }] }] }, { subs: [{ subs: [{}] }] }] }, {}];
console.log(getDepth(data1) - 1); // 0
console.log(getDepth(data2) - 1); // 1
console.log(getDepth(data3) - 1); // 5
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2894 次 |
最近记录: |