0

I was wondering if there is a way of writing the appended function in a shorter way. The only difference between the code that's executed in the conditions is whether the datetime will be set to 00:00:00 (startOf('day')) or 23:59:59 (endOf('day')). This small difference led me to believe that there must be some way of dynamically setting the 3rd function call, but I don't know how.

function moveDateForOneMonth(date, type) {
    if (type == 'startOf') {
      return DateTime.fromJSDate(new Date(date))
        .plus({ month: 1 })
        .startOf('day')
        .toMillis();
    } else {
      return DateTime.fromJSDate(new Date(date))
        .plus({ month: 1 })
        .endOf('day')
        .toMillis();
    }
  }

The type parameter is either called with an argument 'endOf' or 'startOf', which corresponds to the name of the method that should be executed once .plus({month: 1}) is added to the date.

It'd be ideal if I could do something like:

function moveDateForOneMonth(date, type) {
     return DateTime.fromJSDate(new Date(date))
        .plus({ month: 1 })
        .[type]('day')
        .toMillis();
}

I apologise for my bad formatting and thank you for the answer in advance!

Vid
  • 163
  • 1
  • 13
  • 6
    just remove the `.` before `[type]`, your code is good to go – Code Maniac Sep 05 '19 at 11:03
  • 1
    Yes, that would work. But I would argue that I prefer the current version of the function. It's more verbose, yet easier to read. Also somewhat safer since invalid `type` values are simply reduced to `endOf` rather than a cryptic message about calling `undefined`. Not to mention you'd break your IDE's autocompletion and any linters/transpilers that care about data types (if you use those). – Vilx- Sep 05 '19 at 11:07
  • 1
    @Vilx- the OP could refactor out some of the commonality while still leaving it readable, and safe, see e.g. https://gist.github.com/raybellis/3587f104a62a3b78c017d1b90c0fb641 – Alnitak Sep 05 '19 at 11:11
  • 1
    True, but I still find the original more readable. :) Then again, it is a matter of personal taste, so I totally understand if other people want to do it differently. – Vilx- Sep 05 '19 at 11:16

0 Answers0