gastromatic / calendar-date

Immutable object to represent and work with a calendar date with zero dependencies
MIT License
22 stars 1 forks source link

`Set` not correctly removing duplicates #181

Closed celluj34 closed 1 year ago

celluj34 commented 1 year ago

Consider:

const arr = [
  new CalendarDate(2022, 01, 01),
  new CalendarDate(2022, 01, 01)
];

const distinct = [...new Set(arr)];

The variable distinct will have two entries. Is this intended? I do understand they're objects, not primitive values.

I accomplished what I wanted by using reduce and Map, but I feel like it could be simplified somehow.

co-sic commented 1 year ago

Since Set only works for primitive values and object references (works the same as === operator), there is nothing we can do to make it work, since CalendarDate is an object. But you can use a combination of map and Set like this:

const arr = [
  new CalendarDate(2022, 1, 1),
  new CalendarDate(2022, 1, 1)
];

const distinct = [...new Set(arr.map(v => v.toString()))].map(v => new CalendarDate(v));
console.log(distinct.length) // 1
celluj34 commented 1 year ago

Yep, makes sense. I did something similar to accomplish what I did. It's unfortunate we can't override the === operator, that would be the best case.

Thanks for the reply!