On Sunday, 23 October 2022 at 13:32:44 UTC, matheus wrote:
I have a design question and I'd like to hear some advice.
Let's say that I want to create a method to sort an array:
arr.sort(asc);
I think usually this would usually return a new set of that
array but now sorted.
But If I want to do this in the original, I think I would do
this:
arr.sort(asc).save();
The problem with this, it would create a new set and
assign/copy back to the caller, which would be a waste. So I
thought about this:
arr.save.sort(asc);
Then save would tell to "sort()" what to do beforehand, like
passing some argument saying that the sort should be done
direct in the caller and no copy.
Is this (The latter) an approach you would use? Or there is a
better way to do this.
You say your idea is "like passing some argument", so why not
actually pass an argument?
For example:
enum Direction { asc, desc }
enum InPlace : bool { no, yes }
ref Arr sort(ref Arr arr, Direction dir, InPlace inPlace =
InPlace.no)
{
if (inPlace) {
arr.sortInPlace(dir);
return arr;
} else {
return arr.sortedCopy(dir);
}
}
Usage would look like this:
auto sorted = arr.sort(asc); // sorted copy
arr.sort(desc, InPlace.yes); // sort in place