import { Cell } from './Cell'; import * as Fun from './Fun'; import { Optional } from './Optional'; interface Singleton { readonly clear: () => void; readonly isSet: () => boolean; readonly get: () => Optional; readonly set: (value: T) => void; } export interface Repeatable { readonly clear: () => void; readonly isSet: () => boolean; readonly get: () => Optional; readonly set: (functionToRepeat: () => void) => void; } export interface Revocable extends Singleton { } export interface Api extends Singleton { readonly run: (fn: (data: T) => void) => void; } export interface Value extends Singleton { readonly on: (fn: (data: T) => void) => void; } const singleton = (doRevoke: (data: T) => void): Singleton => { const subject = Cell(Optional.none()); const revoke = (): void => subject.get().each(doRevoke); const clear = () => { revoke(); subject.set(Optional.none()); }; const isSet = () => subject.get().isSome(); const get = (): Optional => subject.get(); const set = (s: T) => { revoke(); subject.set(Optional.some(s)); }; return { clear, isSet, get, set }; }; export const repeatable = (delay: number): Repeatable => { const intervalId = Cell(Optional.none()); const revoke = (): void => intervalId.get().each((id) => clearInterval(id)); const clear = () => { revoke(); intervalId.set(Optional.none()); }; const isSet = () => intervalId.get().isSome(); const get = (): Optional => intervalId.get(); const set = (functionToRepeat: () => void) => { revoke(); intervalId.set(Optional.some(setInterval(functionToRepeat, delay))); }; return { clear, isSet, get, set, }; }; export const destroyable = void }> (): Revocable => singleton((s) => s.destroy()); export const unbindable = void }> (): Revocable => singleton((s) => s.unbind()); export const api = void }> (): Api => { const subject = destroyable(); const run = (f: (data: T) => void) => subject.get().each(f); return { ...subject, run }; }; export const value = (): Value => { const subject = singleton(Fun.noop); const on = (f: (data: T) => void) => subject.get().each(f); return { ...subject, on }; };