LCIII
LCIII

Reputation: 3626

How to optionally add a method to a chain in javascript?

I have this chain of methods

MyObject.methodA().methodB().methodC()

Suppose I want methodB() to be added or changed based on some condition:

const inclueMethodB = false;
// change method based on condition
MyObject.methodA().(inclueMethodB ? methodB() : method123()).methodC()
// add method based on condition
MyObject.methodA().(inclueMethodB && methodB()).methodC()

Is there a way to do this in javascript?

Upvotes: 1

Views: 76

Answers (1)

Barmar
Barmar

Reputation: 781068

I can't think of a way to optionally call a method like that.

If you were choosing between two methods, you could use a subscript where the method name is specified dynamically:

MyObject.methodA()[includeB1 ? "methodB1" : "methodB2"]().methodC()

You could achieve your original goal by defining a method that doesn't do anything except return the same thing that methodB() does. If this is a fluent interface where all the methods just return this, it could be:

doNothing() {
    return this;
}

Then you could write:

MyObject.methodA()[includeB ? "methodB" : "doNothing"]().methodC()

But this all seems unnecessarily complex and confusing. Just use ordinary if statements, which express the intent clearly:

let temp = MyObject.methodA();
if (includeB) {
    temp = temp.methodB();
}
temp.methodC();

Upvotes: 1

Related Questions