Fealo
Fealo

Reputation: 99

Transform 2 very similar functions in to one

I have these two functions, which are very very similar :

setEndTimes(pricerules: PriceRule[]) {
    this.endTimes = [];
    pricerules.forEach(pricerule => {
      this.endTimes.push({
        hour: Number(pricerule.endTime.split(':')[0]),
        minute: Number(pricerule.endTime.split(':')[1])
      });
    });
  }

  setStartTimes(pricerules: PriceRule[]) {
    this.startTimes = [];
    pricerules.forEach(pricerule => {
      this.startTimes.push({
        hour: Number(pricerule.startTime.split(':')[0]),
        minute: Number(pricerule.startTime.split(':')[1])
      });
    });
  }

How to transform these 2 functions into one ?

Upvotes: 0

Views: 52

Answers (2)

Taras Yaremkiv
Taras Yaremkiv

Reputation: 3600

You would dynamic properties for this case like:

setTimes(pricerules: PriceRule[], _times: string) {
    this[`${_times}s`] = [];
    pricerules.forEach(pricerule => {
      this[`${_times}s`].push({
        hour: Number(pricerule[_times].split(':')[0]),
        minute: Number(pricerule[_times].split(':')[1])
      });
    });
  }

Upvotes: 1

Kunal Mukherjee
Kunal Mukherjee

Reputation: 5853

You can refactor the code which projects the array from pricerules into a function and set the properties and use bracket notation to access the object property.

setEndTimes(pricerules: PriceRule[]) {
    this.endTimes = returnTimes(pricerules, 'endTime');
}

setStartTimes(pricerules: PriceRule[]) {
    this.startTimes = returnTimes(pricerules, 'startTime');
}

returnTimes(pricerules, time) {
    return pricerules.map(x => (
    {
                    hour: Number(x[time].split(':')[0]),
                    minute: Number(x[time].split(':')[1])
    }));
}

Upvotes: 1

Related Questions