Welcome to Software Development on Codidact!
Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.
Comments on How this recursive treewalker works?
Parent
How this recursive treewalker works?
Credit for User:Meriton for developing the following code (first published here).
function replaceIn(e) {
if (e.nodeType == Node.TEXT_NODE) {
e.nodeValue = e.nodeValue.replaceAll("a", "");
} else {
for (const child of e.childNodes) {
replaceIn(child);
}
}
}
replaceIn(document.body);
How this recursive treewalker works?
As a side question which I grasp as important, can there be an even simpler and more direct version without the else
?
Post
Note: This answer was written for a version of the question that focused on getting rid of the if-else, rather than on an explanation of the workings of the recursive tree-traversal.
One way of getting rid of if-elses to achieve uniform handling of different objects is to hide the distinction in lower levels of abstraction:
Imagine a bowl of apples and bananas. Basically, you just want to eat all of them. However, if you one by one pick the bowl contents, you first have to check if you have a banana - which you need to peel before you bite into it. That is, your algorithm is "for each fruit: if banana, peel then eat, if apple, eat". You can abstract it by introducing a function "prepare_for_eating". Then your algorithm is "for each fruit: prepare_for_eating(fruit) then eat(fruit)". Seems as if the if-else has disappeared. But, if you look inside the "prepare_for_eating" function, you will again have the original if-else statement where you decide to peel or not to peel.
With object oriented techniques you can hide if-elses behind method calls: A Fruit base class would provide a member function "prepare_for_eating". For banana, this would contain the "peel" statement, for the apple, this would be empty. The algorithm would be "for each fruit: fruit.prepare_for_eating then fruit.eat". If fruit happens to be a banana, the banana member function doing the peel would be called. For an apple object, the apple member function would be called that does nothing.
You can use other tricks to get rid of if-elses by computing boolean expressions and use their result as zero or one in multiplications or table lookups. For example:
if x == 42 then x = -1
can be re-written as (assuming true can be used as 1 and false as 0):
x = (x == 42) * -1 + (x != 42) * x;
Or, using such a result for table lookups:
action_table = [peel, do_nothing]
for each fruit: call action_table[fruit is apple] then eat;
Whether any of the above ideas can be applied meaningfully to your problem and is suited to fulfill your expectations is up to you.
2 comment threads