I have experience in adding custom properties to objects.
For example, if I have a method called foo,
const foo = () => { console.log('custom method'); }
I can add the foo
method to the Array prototype and use it with array variables by
Array.prototype.foo = foo;
Then, by creating an array named,
bar = [1, 2, 3];
and calling
bar.foo()
My custom foo method will be executed. However, I am unsure how to automatically run the foo
method every time a new array is created or updated.
I am looking to run a custom method and store data during array creation/update in JavaScript. How can this be achieved?
Imagine I have a custom method,
const customMethod = () => {
...performing some operations
}
I want this custom method to run every time a new array is created, storing additional data such as the maximum value within the array. This way, I can access the maximum value by calling myArray.maximum
without having to recalculate it each time.
A similar approach accomplishes this by adding an event listener and a new push method to trigger an event whenever an item is added to the array using the custom push method. However, the custom function will not be triggered if the regular Array.prototype.push
method is used or when creating a new array using the spread operator like newArr = [...oldArray, value]
.
Update: Further research and the links provided in the comments reveal that directly modifying the Array object without extending it or creating a custom array type from scratch (which is not ideal) is not feasible.
I attempted to extend the existing Array type to create MyCustomArray, but it did not behave as expected.
class MyCustomArray extends Array {
constructor(...args) {
super(...args);
console.log('custom array');
}
}
Is there a way to extend the Array to create a CustomArray type and add a listener so that each time I create/update a CustomArray, it automatically calculates the maximum value and sets it as an array property (with minimal code changes)?
Therefore, my CustomArray would retain all typical array methods and properties but also calculate and store the maximum value each time it is updated/created.