Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chain functions in JavaScript

Is there a way to chain functions in JavaScript so when last function in chain is called we take into consideration all function in chain that was specified. Basically what I am trying to do is the same thing express-validator does: Something like this:

check('password').passwordValidator().optional();

I want to be able to call

check('password').passwordValidator();

and

check('password').passwordValidator().optional();
like image 457
Blz Avatar asked Dec 01 '22 10:12

Blz


2 Answers

So you're looking for a sort of builder pattern? You can do that like this:

class Foo {
  _passwordValidator = false;
  _optional = false;

  passwordValidator() {
    this._passwordValidator = true;
    return this;
  }
  optional() {
    this._optional = true;
    return this;
  }

  doThing() {
    if (this._optional) { /* ... */ }
    if (this._passwordValidator) { /* ... */ }
  }
}

const foo = new Foo().passwordValidator().optional();

foo.doThing();

Edit: to more directly answer your question, there is no way to wait to do something until the current chain of method calls is done; you have to call a method like doThing() in the example to signal that you actually want to do the thing now.

like image 134
coolreader18 Avatar answered Dec 04 '22 00:12

coolreader18


I ended up using what @coolreader18 suggested. That was exactly what I was looking for.

function func(val) {
    this._optional = false;
    this._check = false;
    
    const doStaff = (message = 'Doing staff') => {
        console.log(message);
        return;
    };


    return {
        check: function(n) {
            this._check = true;
            return this;
        },
        optional: function(n) {
            this._check = false;
            this._optional = true;
            return this;
        },
        exec: function() {
            if (this._check) doStaff();
            if (this._optional) doStaff('Maybe not');
        }
    }
}

func().check().optional().exec();
like image 26
Blz Avatar answered Dec 04 '22 01:12

Blz