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?

  • @gun
    link
    22 years ago

    It looks like the class Node doesn’t contain any methods, so the only reason why Parent and Leaf would inherit from it is for polymorphism. You can just remove, “extends Node” and everything will work if I understand the problem correctly.

  • @N0b3d
    link
    12 years ago

    I suspect the answer is in the chapter… What’s the chapter about?

    • @2br02bOP
      link
      12 years ago

      Book: Modern Javascript for the Impatient

      Chapter: Object-Oriented Programming