Search code examples
javascriptobjectmethod-chaining

how to do method chaining in object oriented Javascript?


I am trying to do method chaining but it is returning undefined on the second method. I have added return inside each function so I'm not sure why it would return undefined. here is my code

var expertSurfLevel = []
var noviceSurfLevel = []
var IntermediateSurfLevel = []

class SurfSpots {
    constructor() {
    this.windSpeed = [-1.3, 1.34, 2.51, -2.55],
    this.totalWindSpeed = 0
  }
            expert(totalWindSpeed) {
            if (totalWindSpeed.some(num => num < 0) === false) {
              return expertSurfLevel.push(this.coords);
            }
          }
          novice(totalWindSpeed) {
            if (totalWindSpeed >= -5 || totalWindSpeed <= 15) {
              return noviceSurfLevel.push(this.coords);
            }
          }
          intermediate(totalWindSpeed) {
            if (totalWindSpeed >= 5 || totalWindSpeed <= 20) {
              return IntermediateSurfLevel.push(this.coords);
            }
          }
}

var surfSpot = new SurfSpots();
surfSpot.expert(surfSpot.windSpeed).novice(surfSpot.totalWindSpeed).intermediate(surfSpot.totalWindSpeed)
console.log("surfSpot",surfSpot)

I have added on Jfiddle


Solution

  • push returns the new length of the array, which is not what you want. Return the instance (this) instead:

    var expertSurfLevel = []
    var noviceSurfLevel = []
    var IntermediateSurfLevel = []
    
    class SurfSpots {
      constructor() {
        this.windSpeed = [-1.3, 1.34, 2.51, -2.55],
          this.totalWindSpeed = 0
      }
      expert(totalWindSpeed) {
        if (totalWindSpeed.some(num => num < 0) === false) {
          expertSurfLevel.push(this.coords);
        }
        return this;
      }
      novice(totalWindSpeed) {
        if (totalWindSpeed >= -5 || totalWindSpeed <= 15) {
          noviceSurfLevel.push(this.coords);
        }
        return this;
      }
      intermediate(totalWindSpeed) {
        if (totalWindSpeed >= 5 || totalWindSpeed <= 20) {
          IntermediateSurfLevel.push(this.coords);
        }
        return this;
      }
    }
    
    var surfSpot = new SurfSpots();
    surfSpot
      .expert(surfSpot.windSpeed)
      .novice(surfSpot.totalWindSpeed)
      .intermediate(surfSpot.totalWindSpeed)
    console.log("surfSpot", surfSpot)

    It's kind of strange for an instance to mutate independent outside variables, though - consider mutating instance variables instead (eg, create this.expertSurfLevel, etc in the constructor, and push to it), or if you wanted the arrays to be shared among all instances, then use a static property (eg SurfSpots.expertSurfLevel = []).