tc39 / proposal-array-unique

ECMAScript proposal for Deduplicating method of Array
138 stars 7 forks source link

How to deal with empty items #6

Open hax opened 4 years ago

hax commented 4 years ago

What [1, , 2, , , 2, 1].unique() should return?

At least there are three options:

  1. Treat empty items as undefined, so returns [1, undefined, 2]. This matches what [...new Set(arr)] do as README, but I suppose it's not intentional. Note if unique(f), f would be called on every empty items as undefined, (or called with no param?) (To avoid runtime error, if f is a key, I guess it should be treat as x => x?.[key])
  2. Skip all empty items and keep them, so returns [1, , 2, , , ,]
  3. Skip all empty items and drop them, so returns [1, 2]

Personally I prefer the last option.

ljharb commented 4 years ago

It’s intentional from array spread, as in most new array methods, to pretend sparse arrays don’t exist, and to treat them as undefined as well.

jridgewell commented 4 years ago

It’s intentional from array spread, as in most new array methods, to pretend sparse arrays don’t exist, and to treat them as undefined as well.

Can you specify which array methods? As far as I know, for every array method, the predicate is skipped when the item is empty. That would be option 3 here.

hax commented 4 years ago

as in most new array methods

Very interesting... So I checked the "new array methods"

So at least copyWithin and flat/flatMap still respect empty items.

I feel unique is much closer to filter, flat cases.

And if someone really want treat empty items as undefined, they could use [...arr].unique() 🤓

TechQuery commented 4 years ago

@hax As the semantic of unique, [1, undefined, 2] maybe make sense. If someone needs the 3rd option, array.filter(Boolean).unique() is easy for him/her.

hax commented 4 years ago

@TechQuery Ideally no one should use arrays with empty slots anymore. It's unclear whether empty slots have different meaning with intentional undefined item in specific usage, so I think it's very hard to say which one make much sense. The point here is which behavior should be used in unique by default. In either choice, developers need a extra operation if they want another semantic.