skip to Main Content

I have extended class from Map:

class ModifiedMap extends Map {
  constructor(arg) {
    super(arg);
  }
  set(key, value) {
    console.log("doing some work here")
  }
}

And if I try to create ModifiedMap, I see "doing some work here" printing n times (depends on iterator).

new ModifiedMap([["a", "apple"],["b", "orange"],["c", "banana"]])

How can I avoid using my subclass’s set method in the internal algorithm of constructing Map? Sure I could rename from set to any name, but I want to know is it possible use the same name?

2

Answers


  1. You could use a flag to tell your subclass set whether the instance construction is complete, then check that flag in set. If the flag isn’t set, pass the call on to super.set:

    class ModifiedMap extends Map {
        constructor(arg) {
            super(arg);
            this.ready = true;
        }
        set(key, value) {
            if (this.ready) {
                console.log("doing some work here");
            } else {
                return super.set(key, value);
            }
        }
    }
    
    console.log("Constructing...");
    const map = new ModifiedMap([["a", "apple"],["b", "orange"],["c", "banana"]]);
    console.log("Done constructing, adding an entry");
    map.set("x", "y");

    That said, it seems fairly odd to bypass your subclass’s customized set only during construction. A separate method specific to the subclass may be a better idea.

    Login or Signup to reply.
  2. A variation of @T.J.Crowder’s solution is to add the flag to the overriden method. Internal calls will not provide this flag, but your custom calls can pass it conditionally.

    class ModifiedMap extends Map {
        set(key, value, dowork) {
            if (dowork !== undefined) {
                console.log("doing some work here");
            } else {
                return super.set(key, value);
            }
        }
    }
    
    console.log("Constructing...");
    const map = new ModifiedMap([["a", "apple"],["b", "orange"],["c", "banana"]]);
    console.log("Done constructing, adding an entry");
    map.set("x", "y", true);  // <-- pass something when calling set
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search