As I delve into prototyping, I encountered an issue with using forEach and reduce on my ArraySet prototype. The arrow function callback works well with forEach, but I hit a roadblock with reduce. It seems the notation that works for a normal Array doesn't quite translate to my prototype. I also tried using arrow notation, but that didn't work either.
I'm wondering what I'm missing in my understanding of this situation and how I can resolve it.
function ArraySet(items) {
// this._items = []
this._items = items
}
ArraySet.prototype.forEach = function forEach(cb) {
return this._items.forEach(cb);
}
ArraySet.prototype.reduce = function reduce(cb) {
return this._items.reduce(cb);
}
let arr = new ArraySet([{
key1: 'property2',
key3: 'propertyx'
},
{
key1: 'property4',
key3: 'propertyy'
},
{
key1: 'climate change',
key3: 'propertyx'
},
{
key1: 'climate change',
key3: 'propertyx'
},
])
arr.forEach(el => {
console.log(el)
});
x = arr.reduce(function (map, obj) {
if (obj.key3 === 'propertyx'){
map.push(obj.key1)
}
return map
}, []) //<-- final argument is the instantiating literal of the reigning map type: [], {}, ''
EDIT: Thanks to Maheer Ali's insights on using the spread operator (...), I was able to solve the problem easily. Maheer also sheds light on other functions where this approach can be applied.
On further investigation, I discovered that before the spread operator, .apply() was commonly used in function calls to ensure all necessary arguments were available during execution. The spread operator has evolved from initially applying to arrays (like a list of arguments) to now encompassing objects. It can also copy an array, replacing arr.splice().
Here's an example adapted from the MDN:
function myFunction(v, w, x, y, ...z) {
console.log(v + ' ' + w + ' ' + x + ' ' + y + ' ' + z)
}
var args = [0, 1];
myFunction(-1, ...args, 2, ...[3, 8]);
For more information, refer to the documentation on Spread Syntax