Lab
Object pool
type Thumbnail = { name: string; flipX?: boolean };
class Session {
id: number;
flipX = false;
constructor(id: number) {
this.id = id;
}
}
// The pool: every session made once, lent to one job at a time.
class SessionPool {
private idle: Session[] = [];
constructor(size: number) {
for (let id = 1; id <= size; id++) this.idle.push(new Session(id));
}
acquire(): Session | null {
return this.idle.shift() ?? null;
}
release(session: Session): void {
session.flipX = false;
this.idle.push(session);
}
}
// One job on a borrowed session. An omitted flipX keeps the session's setting.
function job(session: Session | null, thumbnail: Thumbnail): string {
if (!session) return `${thumbnail.name}: no session free`;
if (thumbnail.flipX !== undefined) session.flipX = thumbnail.flipX;
const look = session.flipX ? 'mirrored' : 'original';
return `${thumbnail.name}: session ${session.id}, ${look}`;
}
const pool = new SessionPool(2);
const first = pool.acquire();
const second = pool.acquire();
const third = pool.acquire();
const a = job(first, { name: 'A', flipX: true });
const b = job(second, { name: 'B' });
const c = job(third, { name: 'C' });
if (first) pool.release(first);
if (second) pool.release(second);
const retry = pool.acquire();
const cRetry = job(retry, { name: 'C' });
console.log([a, b, c, cRetry].join('\n'));
TODO
Visual to come