0

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

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Code Ninja
  • 157
  • 4
  • 13
  • You did add some `return`, yeah, but *what* do you return? Is it an object that has the chainable method? – Bergi Jul 06 '19 at 11:01
  • Method-chaining is way overhyped. I wouldn't build an API around it. Use return values that make sense for the method. – ziggy wiggy Jul 06 '19 at 11:06

1 Answers1

2

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 = []).

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320