← Multiton lesson
Lab

Multiton

type Channel = { room: string; id: number; gain: number };

// The owner: one retained channel per room, for one mixing session.
function createRoomChannels(initialGain: number) {
  const entries = new Map<string, Channel>();
  let created = 0;
  return {
    get(room: string): Channel {
      let channel = entries.get(room);
      if (!channel) {
        created++;
        channel = { room, id: created, gain: initialGain };
        entries.set(room, channel);
      }
      return channel;
    },
    forget(room: string): boolean {
      return entries.delete(room);
    },
  };
}

const mixA = createRoomChannels(80);
const consoleStudio = mixA.get('studio');
const lounge = mixA.get('lounge');
consoleStudio.gain = 30;
const forgotten = mixA.forget('lounge');
const remoteStudio = mixA.get('studio');
const shared = consoleStudio === remoteStudio;
const mixB = createRoomChannels(80);
const otherSession = mixB.get('studio');

const show = (name: string, c: Channel) =>
  console.log(`${name}: ${c.room} #${c.id} gain=${c.gain}`);
show('console', consoleStudio);
show('remote', remoteStudio);
show('lounge', lounge);
show('mix B', otherSession);
console.log(`shared: ${shared}, forgotten: ${forgotten}`);