Array.prototype.toFilled and ... .toCopiedWithin?

The lack of non-mutating method alternatives for Array.prototype.fill and .copyWithin has bugged me for a while. And while I understand that .fill is mostly used in expressions like Array(length).fill(0) where a non-mutating method would make no difference, it can also have other uses following the array creation (e.g. partially fill an array).

Similar argument for .copyWithin, although .toCopiedWithin might sound awkward (name suggestions are welcome).

Trivial polyfills:

Array.prototype.toFilled = function toFilled(...args) {
  return this.slice().fill(...args);
};
Array.prototype.toCopiedWithin = function toCopiedWithin(...args) {
  return this.slice().copyWithin(...args);
};

Just a note: methods like .toReversed and the like always return dense arrays, while .slice does not. Should .toCopiedWithin “densify” the returned array?

Of course, the same methods would be available in TypedArrays too.

Hi @MaxArt - I was the champion of the Change-array-by-copy proposal that added .toSorted() and toReversed().

The proposal originally added non mutating versions of all mutating methods but we agreed to reduce the scope.

Very interesting insights, thank you @aclaymore .

Nevertheless, I’ve found working around the lack of .toFilled particularly annoying, although it could be just me. Do you think there’s ground the decision could be revisited - about .fill at least?

The case would need to be made why .slice().fill(v) or .map(() => v) (if the array is already dense) are not sufficient and a common enough problem to prompt the addition of a new method.

A common starting point is searching open source to find how common a problem may be. For example: Researching existing code corpora · Issue #37 · tc39/proposal-change-array-by-copy · GitHub which, at the time, showed fill and copyWithin appeared in the fewest repositories.

2 Likes