Self Learning: Rewrite this code in Javascript without using inheritance.
Self Learning: Rewrite this code in Javascript without using inheritance.
I have been reading a book on JS. This is one of the questions at the end of a chapter that stumped me; don't know where to begin. So please help me out:
Question
A classic example for an abstract class is a tree node. There are two kinds of nodes: those with children (parents) and those without (leaves).
class Node { depth() { throw Error("abstract method") } } class Parent extends Node { constructor(value, children) { . . . } depth() { return 1 + Math.max(...children.map(n => n.depth())) } } class Leaf extends Node { constructor(value) { . . . } depth() { return 1 } }
This is how you would model tree nodes in Java or C++. But in JavaScript, you don’t need an abstract class to be able to invoke n.depth().
Rewrite the classes without inheritance and provide a test program.
So, how to write this code without using inheritance in JS?