tc39/proposal-change-array-by-copy

Extra param alternative?

Rudxain opened this issue · 4 comments

What if instead of adding new methods, we just add a new parameter that takes a Boolean argument that specifies whether to copy or mutate? This could also be added to other methods like fill, filter, flat, map, and slice. This would simplify code like this:

arr = arr.slice(i0, i1)

Into this

arr.slice(i0, i1, true)

That way, every Array method will be capable of mutation and shallow copying, and devs could explicitly specify which behavior they want. Instead of a Bool arg, it could be strings (for readability) like 'mut' & 'copy'.

arr = arr.map(_ => _, null, 'copy')
//is equivalent to
arr.map(_ => _, null, 'mut')

The problem with this is that some methods are variadic, so they can't have an extra param, and would require a new fn. This is the case of concat, push, and some others

What happens with arr.slice(x)? What about with map and other array methods that take a callback, which already takes an optional "receiver" argument?

Even if this were an ergonomic or idiomatic pattern (it is neither), it's simply not viable.

What about other array methods that take a callback, which already takes an optional "receiver" argument?

I think I get what you mean. The callback fn may already do the mutation by itself, no need for an extra param.

Even if this were an ergonomic or idiomatic pattern (it is neither), it's simply not viable.

I don't understand this, what do you mean by "idiomatic"? (Is it related to programming idioms?). And I understand why it's not viable, it's probably because of scalability and consistency issues

Hi @Rudxain

One of the goals of this proposal is for Arrays to share a common interface with immutable lists. This enables code to work across multiple underlying types. e.g.:

function sortByAge(list) {
  // 'list' can be an array or a tuple - both will work as both have the 'toSorted' method
  return list.toSorted((a, b) => a.age - b.age);
}

With the boolean-parameter idea, immutable lists would have a .sort method but where the flag must always be set to create a copy otherwise it will error. The default could be to create a copy by default, but this would not be backwards compatible with the existing methods like sort which do not make a copy by default.

I understand now. The bool param would be problematic. Thank you for the info