It should be quite easy to implement array.map()
that is defined in ECMA-262, which takes a function and this function will be called by 3 arguments: element value, index, the array.
But what about for sparse array? Obviously we don't want to iterate from index 0 to 100,000 if only index 0, 1, 2, and 100,000 has an element and otherwise is sparse from index 3 to 99,999. I can think of using arr.slice(0)
or arr.concat()
to clone the array, and then put in the replaced values, but what if we don't use slice
or concat
, is there another way to do it?
The solution I came up with using slice()
is:
Array.prototype.collect = Array.prototype.collect || function(fn) {
var result = this.slice(0);
for (var i in this) {
if (this.hasOwnProperty(i))
result[i] = fn(this[i], i, this); // 3 arguments according to ECMA specs
}
return result;
};
(collect
is used to try out the code, as that's another name for map
in some language)