Chaining Functions in Javascript

Chaining Functions in Javascript

When you're chaining a function, it's important to return this. If you're not sure what this is, read about it here..

Make it with a class structure:

class ChainMaker {
  _value = "";

  addLetter(letter) {
    this._value += letter;
    return this;
  }
  removeLetter(letter) {
    this._value = this._value.replaceAll(letter, "");
    return this;
  }
  getOutput() {
       return this._value;
  }
}
const output = 
  new ChainMaker()
      .addLetter('hail')
      .removeLetter('a')
      .removeLetter('l')
      .getOutput(); 
console.log(output)

Or a functional structure:

const ChainMaker = () => {
    let _value = "";

    return {
        addLetter: function(letter) {
            _value += letter;
            return this;
        },
        removeLetter: function(letter) {
            _value = _value.replaceAll(letter, "");
            return this;
        },
        getOutput: function() {
            return _value;
        }
    }
}
const output = ChainMaker()
    .addLetter('hail')
    .removeLetter('a')
    .removeLetter('l')
    .getOutput(); 
console.log(output);

Or an object structure:

const ChainMaker = {
    _value: "",
    addLetter: function(letter) {
        this._value += letter
        return this;
    },
    removeLetter: function(letter) {
        this._value = this._value.replaceAll(letter, "");
        return this;
    },
    getOutput: function() {
        return this._value;
    }
}
const output = ChainMaker
    .addLetter('hail')
    .removeLetter('a')
    .removeLetter('l')
    .getOutput();