sorted here is not a function, but the result of calling the anonymous function function (arr) { return arr.sort(function(a, b) { return a - b }) } with the value [...this.array]. So it is not itself a function that will be called again.
PS: should i be doing this? or would it be better to wait until i actually need max, min, etc. and only then get the values?
That will of course depend upon your application. If you're likely to never need them, then it might make sense to wait. But if you will likely need any of them, especially if you're going to use them more than once, then, since the only expensive operation in there is sorted, which is used in some others anyway, you might as well do it up front. The code is much cleaner this way.
But speaking of clean code... if you don't need the prototype of this object (you're not adding methods to this type, that is), then it might be cleaner to create this with a factory function (and thus skip the new operator.) Here is one version:
const myArrayObj = (array, sorted = [... array].sort()) => ({
array,
sorted,
max: sorted[sorted.length - 1],
min: sorted[0],
sum: array.reduce((a, b) => a + b, 0),
unique: [... new Set(sorted)]
})
If you don't like to have sorted defined that way, then you could make it
const myArrayObj = (array) => {
const sorted = [... array].sort())
return {
array,
// ...
}
}
One other point. If you need sorted for itself, this is fine. But if you want sorted only to get max and min, then there is a real inefficiency in doing an O(n * log(n)) operation to get values which you could collect in O(n) ones. Depending upon your data, this may never be an issue, but it's worth considering.
this.sorted = [...this.array].sort(function(a, b) { return a - b }). Why the immediately involved functions?popthe last value? Why not just return the last element with something likethis.sorted[this.sorted.length - 1]