0

Why does Code Snippet 1 work while Code Snippet 2 doesn't?

Code Snippet 1:

var firstEvents = events.reduce(function(ar, e) {
  var id = e.getId();
  if (e.isRecurringEvent() && e.isAllDayEvent() && !ar.some(function(f) {return f.eventId == id})) {
    ar.push({eventTitle: e.getTitle(), eventId: id, startDate: e.getAllDayStartDate(), endDate: e.getAllDayEndDate()});
  }
  return ar;
}, []);
firstEvents = new Map(firstEvents.map(entry => [entry.eventTitle, entry.startDate]));

Code Snippet 2:

var firstEvents = events.reduce(function(ar, e) {
  var id = e.getId();
  if (e.isRecurringEvent() && e.isAllDayEvent() && !ar.some(function(f) {return f.eventId == id})) {
    ar.push({eventTitle: e.getTitle(), eventId: id, startDate: e.getAllDayStartDate(), endDate: e.getAllDayEndDate()});
  }
  return (new Map(ar.map(entry => [entry.eventTitle, entry.startDate])));
}, []);

How would I shorten Code Snippet 1 correctly?

1 Answer 1

1

Why does Code Snippet 1 work while Code Snippet 2 doesn't?

Because the callback is executed multiple times, and the new Map you are returning becomes the ar accumulator value in the next call.

How would I shorten Code Snippet 1 correctly?

To make it a single expression, you would use

const firstEvents = new Map(events.reduce(…).map(…));

But really the correct solution would be not to use reduce and push at all, but just map and filter. To remove duplicate ids, keep track of them in a Set, or even better just key another map by them:

const firstEventsById = new Map(events.filter(e =>
  e.isRecurringEvent() && e.isAllDayEvent()
).map(e => {
  var id = e.getId();
  return [id, {
    eventTitle: e.getTitle(),
    // eventId: id,
    startDate: e.getAllDayStartDate(),
    // endDate: e.getAllDayEndDate()
  }];
}).reverse());
const startDatesByTitle = new Map(Array.from(firstEventsById.values(), entry =>
  [entry.eventTitle, entry.startDate]
));
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! Could you give me a live example using map and filter?
Thank you very much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.