Reusing a date object in momentjs

I have a Javascript collection that am filtering. In the callback I am instantiating a new moment object which breaks the filter function.

var today = new moment().format('YYYY-MM-DD');
return this.collection.filter((vocab) => {
  let benchmarkDate = new moment(vocab.interval_benchmark_date).format();

  return benchmarkDate.isAfter(today);
});

Is it possible to instantiate the moment object before the filter and then reuse it in each iteration of the filter callback be resetting it with each new date?

Upvotes: 0

Views: 178

Answers (1)

Deryck
Deryck

Reputation: 7668

TLDR - remove .format() from let benchmarkDate = new moment(vocab.interval_benchmark_date).format(); and your filtering should work again. .format() creates a date string value, not a moment object like it was before, so it does not have access to the original moment methods like .isAfter()


Is it possible to instantiate the moment object before the filter and then reuse it in each iteration of the filter callback be resetting it with each new date?

Yes, and you most certainly should do this as moment() used in high quantities (loops like this possibly) incurs a non-trivial cost that may end up becoming your bottleneck in performance down the road. The less moment() calls you make, the better. Re-use everywhere you can (except when modifying with .add(), etc. because moment will mutate the data directly)

However in your particular instance here - your iteration of different date/time info is what is creating the different moments, which you could potentially avoid by mutating the same moment on every iteration (by using a .reduce() method to continuously work with the previous result)


Also, you are doing let benchmarkDate = ...format() which creates a string and then you attempt to run .isAfter() on it - which won't exist because it's not the Moment object anymore. Since the result of the .format() is unused anyway, you can remove that and it should be fine.


Oh and the moment() function does not require the new keyword to return the object.

Upvotes: 1

Related Questions