Your method is already looks good! I would only make a couple small changes to the logic. as follows:
- The
if (this._children.length > 0)isn't necessary as the for loop will will make the check for you. - Instead of using a standard for loop, I would prefer a
for..ofloop loop. Typescript will transpile this so it will work in any environment. environment - I prefer early returns to nested statements. Because of this, I would
would recommend storing the
resultvariable in as small a block as possible. possible
With these changes:
public findNode = (id: any): TreeNode => {
if (this._id === id) {
return this;
}
for (const child of this._children) {
const result = child.findNode(id);
if (result) {
return result;
}
}
return null;
}
Also, here's a couple Typescript specific notes:
Avoid
Avoidanylike the plague. When you useanyyou are telling typescript to effectively ignore any mistakes in your code. Given your data structure, it looks likeidshould be of typestring.anylike the plague. When you useanyyou are telling typescript to effectively ignore any mistakes in your code. Given your data structure, it looks likeidshould be of typestringI highly recommend turning on
I highly recommend turning onstrictNullChecks. This will help prevent a large class of errors.strictNullChecks. This will help prevent a large class of errorsMethods are public by default in Typescript, with this in mind I recommend dropping the
Methods are public by default in Typescript, with this in mind I recommend dropping thepublicmodifier in most cases as it is redundant. However, this does not apply if you are working on a team with developers who generally work with other languages as it could lead to confusion in the team. (For example, in C# the default is that all methods areprivate).publicmodifier in most cases as it is redundant. However, this does not apply if you are working on a team with developers who generally work with other languages as it could lead to confusion in the team. For example, in C# the default is that all methods areprivate
With these changes:
findNode = (id: string): TreeNode | null => {
if (this._id === id) {
return this;
}
for (const child of this._children) {
const result = child.findNode(id);
if (result) {
return result;
}
}
return null;
}