Array Push Event
// Question// Level ->> Medium// Asked in PharmEasy
// Attach event on push element in an array ?
//Solutionconst originalPush = Array.prototype.push;
// Modify the push methodArray.prototype.push = function (...args) { const result = originalPush.apply(this, args); if (this.onPush) { this.onPush(args); } return result;};
Array.prototype.setPushCb = function (callback) { if (typeof callback === 'function') { this.onPush = callback; // Store the callback function on the array } else { throw new TypeError('Callback must be a function'); }};
// Testconst arr = [];arr.setPushCb((items) => { console.log('Items pushed:', items);});
arr.push(1);arr.push(2, 3);