convert similar computed properties to use just one

Viewed 42

I have those 3 computed properties is it possible to make them in just one ?

    first() {
      const mydate1 = new Date();
      mydate1.setDate(mydate1.getDate() + 1);
      return mydate1;
    },
    second() {
      const mydate2 = new Date();
      mydate2.setDate(mydate2.getDate() + 2);
      return mydate2;
    },
    third() {
      const mydate3 = new Date();
      mydate3.setDate(mydate3.getDate() + 3);
      return mydate3;
    },    

2 Answers

This is perfectly okay for a computed property...

dates() {
  const baseDate = new Date().getDate();

  const first = new Date();
  first.setDate(baseDate + 1);

  const second = new Date();
  second.setDate(baseDate + 2);

  const third = new Date();
  third.setDate(baseDate + 3);

  return { first, second, third };
},    

Previous references to, say, second, can change to dates.second. Same for all three.

Instead of using computed properties, why not make a method getDate(offset) that returns a new Date?

methods: {
  getDate(offset) {
    const myDate = new Date();
    myDate.setDate(myDate.getDate() + offset);
    return myDate;
  }
}
Related