I don't know if this is a silly idea. But let's say I have an array, I keep pushing new elements to it. And I want to set up logic so that any element that exists for 5 minutes will be automatically removed from that array.
Any idea for the solution?
Note that I don't want to keep the timestamp for any element, I want them to be removed automatically.
You can create your own array class and every time you push element you setTimeout
its removal. Here we push a new element every second and they are automatically removed (without shifting the remainig elements) in 5 seconds.
class MyArray extends Array {
push() {
const i1 = this.length;
const i2 = super.push(...arguments);
setTimeout(() => {
for (let i=i1; i<i2; i++) delete this[i];
},5000);
return i2;
}
}
let a = new MyArray();
let i = 0;
let t1 = setInterval(() => { a.push(i++); console.log(a); }, 1000);
setTimeout(() => {
clearInterval(t1);
}, 60000)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With