UNPKG

shelving

Version:

Toolkit for using data in JavaScript.

50 lines (49 loc) 1.54 kB
import { UnexpectedError } from "../error/UnexpectedError.js"; import { BLACKHOLE } from "./function.js"; /** Callback function that does nothing and returns a blackhole stop callback. */ export const STOPHOLE = () => BLACKHOLE; /** * Wrapper class to handle state on start/stop callback process. * - If process has already started, `starter.start()` won't be called twice (including if `start()` didn't return a `stop()` callback). */ export class Starter { _start; _started = false; _stop = undefined; constructor(start) { this._start = start; } start(...values) { if (this._started) return; try { this._stop = this._start(...values); this._started = true; } catch (thrown) { throw new UnexpectedError("Unexpected error in start callback", { cause: thrown, caller: this.start }); } } stop() { if (!this._started) return; try { if (typeof this._stop === "function") this._stop(); } catch (thrown) { throw new UnexpectedError("Unexpected error in stop callback", { cause: thrown, caller: this.stop }); } finally { this._started = true; this._stop = undefined; } } [Symbol.dispose]() { this.stop(); } } /** Get a `Starter` from a `PossibleStarter` */ export function getStarter(start) { return typeof start === "function" ? new Starter(start) : start; }