62 lines
1.5 KiB
JavaScript
62 lines
1.5 KiB
JavaScript
class ObjectPool {
|
|
constructor(createFn, resetFn) {
|
|
this.createFn = createFn; // Funkcija za kreiranje novega objekta
|
|
this.resetFn = resetFn; // Funkcija za resetiranje objekta pred ponovno uporabo
|
|
this.active = []; // Aktivni objekti
|
|
this.inactive = []; // Neaktivni objekti (v poolu)
|
|
}
|
|
|
|
// Dobi objekt iz poola
|
|
get() {
|
|
let item;
|
|
if (this.inactive.length > 0) {
|
|
item = this.inactive.pop();
|
|
} else {
|
|
item = this.createFn();
|
|
}
|
|
|
|
// Resetiraj objekt (npr. nastavi visible = true)
|
|
if (this.resetFn) {
|
|
this.resetFn(item);
|
|
}
|
|
|
|
this.active.push(item);
|
|
return item;
|
|
}
|
|
|
|
// Vrni objekt v pool
|
|
release(item) {
|
|
const index = this.active.indexOf(item);
|
|
if (index > -1) {
|
|
this.active.splice(index, 1);
|
|
this.inactive.push(item);
|
|
}
|
|
}
|
|
|
|
// Vrni vse aktivne v pool
|
|
releaseAll() {
|
|
while (this.active.length > 0) {
|
|
const item = this.active.pop();
|
|
this.inactive.push(item);
|
|
}
|
|
}
|
|
|
|
// Počisti vse
|
|
clear() {
|
|
this.active = [];
|
|
this.inactive = [];
|
|
}
|
|
|
|
// Info
|
|
getStats() {
|
|
return {
|
|
active: this.active.length,
|
|
inactive: this.inactive.length,
|
|
total: this.active.length + this.inactive.length
|
|
};
|
|
}
|
|
}
|
|
|
|
// Ensure global access
|
|
window.ObjectPool = ObjectPool;
|