All files get-startable-stoppable.ts

100% Statements 40/40
100% Branches 9/9
100% Functions 5/5
100% Lines 40/40

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 411x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 9x 9x 9x 9x 9x 3x 3x 9x 9x 6x 1x 1x 5x 5x 5x 5x 5x 9x 9x 3x 1x 1x 2x 2x 2x 2x 9x 9x  
export type Stopper = () => void;
export type Starter = () => Stopper;
 
export interface StartableStoppable {
  readonly started: boolean;
  start: () => void;
  stop: () => void;
}
 
type StartableStoppableState = "stopped" | "started" | "starting";
 
export function getStartableStoppable(id: string, startAndGetStopper: Starter): StartableStoppable {
  let stop: Stopper;
  let state: StartableStoppableState = "stopped";
 
  return {
    get started() {
      return state === "started";
    },
 
    start: () => {
      if (state !== "stopped") {
        throw new Error(`Tried to start "${id}", but it is already ${state}.`);
      }
 
      state = "starting";
      stop = startAndGetStopper();
      state = "started";
    },
 
    stop: () => {
      if (state !== "started") {
        throw new Error(`Tried to stop "${id}", but it is already ${state}.`);
      }
 
      stop();
      state = "stopped";
    },
  };
}