this post was submitted on 08 Oct 2021
1 points (100.0% liked)

learnjavascript

160 readers
0 users here now

  1. Be Welcoming. n00bs are welcome here. Negativity is not.

  2. Include Context If you’re asking for help, include enough information for others to recreate your problem.

  3. No unvetted self promotion Message the mods first.

founded 4 years ago
MODERATORS
 

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?

no comments (yet)
sorted by: hot top controversial new old
there doesn't seem to be anything here