0

Fairly new to using a prototype design pattern so I had a quick question about the most efficient way of creating a setter/getter for multiple constructor variables.

Say I had a "trip" object :

function trip(){
    this.numberOfDays = 0
    this.price = 0
    this.activites = [] 
    this.bPacks = []
    this.pPacks = []
}

Now the setters for the activities, bPacks, and pPacks all do primarily the same thing. They will add or remove to the array that they are associated with.

so instead of writing 6 separate setters for these properties such as :

trip.prototype.addActivity = function(itemToAdd){
  var index = this.activites.push(itemToAdd)
}

trip.prototype.addBPack = function(itemToAdd){
      var index = this.bPack.push(itemToAdd)
    }

etc...

Is it possible to do something like this :

trip.prototype.addPacksOrActivity = function(item,typeOfItem){
    this.typeOfItem.push(item);
} 

where we target the specific property of the trip object we want to push to?

Any suggestions for more efficient ways of building setters/getters are welcome but I am trying to avoid transpiling from ES6 so ES5 type answers are preffered.

dpat
  • 45
  • 6
  • 4
    First of all: [KISS](https://en.wikipedia.org/wiki/KISS_principle). Do you really need individual getters and setters? `myTrip.activities.push(…)` won't do? And if not: you should worry about your outward facing API first and foremost. Do you really want `myTrip.addPacksOrActivity(foo, 'pPacks')`…?! Looks terrible. – deceze Aug 31 '16 at 14:15
  • @deceze I can see your point. The use case here is a really long form that can be changed multiple times ( if say the user went back and forth to change their choices ) . At the moment the code is terrible and I am looking for more structured design patterns. I can see an alternative being using a Hash and just retrieving/setting using Trip.price = foo , etc. – dpat Aug 31 '16 at 14:38

1 Answers1

0

Yes, you can use a simple loop to do that:

["activities", "bPacks", "pPacks"].forEach(function(typeOfItem) {
     var methodName = "add"+typeOfItem[0].toUpperCase()+typeOfItem.slice(1);
     Trip.prototype[methodName] = function(item) {
         this[typeOfItem].push(item);
     };
});

Notice the use of bracket notation and the closure over typeOfItem.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375