Simon Andersson
Simon Andersson

Reputation: 375

How can I call functions conditionally in function chaining?

I don't know what it's called, but in the canvas library i'm using you apply filters to a texture by calling

canvas.draw(texture).filter1().filter2().filter3().filter4();

and i'm trying to only draw certain filters if the value is not default, but i can't do it with regular if statements since the texture can only be set once, and if i try to set it again, the previous filter will get reset.

What i'm wondering is if i can somehow add "if" statements to the "train" of filters, like so:

canvas.draw(texture).if(something){filter1()}.if(somethingelse){filter2()}.if(something){filter3()};

and so on.

Sorry if i'm not very clear, i dont know what the filter "train" is called, where you apply filter after eachother on one line.

Upvotes: 1

Views: 46

Answers (1)

thefourtheye
thefourtheye

Reputation: 239443

The construct you have shown in the question is called, function chaining. The function filter1, filter2, ... filterN would just modify the same canvas object and return the same object at the end of the function.

You can very well include if conditions, like this

var canvasObject = canvas.draw(texture);

if (condition1) {
    canvasObject = canvasObject.filter1();
}

if (condition2) {
    canvasObject = canvasObject.filter2();
}

...

A simple example for the same, would look something like this

function Canvas() {

    actualCanvas = "";

    return {
        filter1: function() {
            actualCanvas += "filter1 ";
            return this;               // return the same object
        },
        filter2: function() {
            actualCanvas += "filter2 ";
            return this;               // return the same object
        },
        filter3: function() {
            actualCanvas += "filter3 ";
            return this;               // return the same object
        },
        getActualCanvas: function() {
            return actualCanvas;
        }
    }
}

And invoke the functions, like this

var canvasObject = new Canvas();

if (1 === 1) {
    canvasObject = canvasObject.filter1();
}

if (1 !== 1) {
    canvasObject = canvasObject.filter2();
}

if (2 === 2) {
    canvasObject = canvasObject.filter3();
}

console.log(canvasObject.getActualCanvas());
// filter1 filter3 

console.log(new Canvas().filter1().filter2().filter3().getActualCanvas());
// filter1 filter2 filter3 

Upvotes: 4

Related Questions