Skip to content

Instantly share code, notes, and snippets.

@Lucifier129
Created July 31, 2021 01:57
Show Gist options
  • Save Lucifier129/069a9d89982a2b51555483a73bb74af5 to your computer and use it in GitHub Desktop.
Save Lucifier129/069a9d89982a2b51555483a73bb74af5 to your computer and use it in GitHub Desktop.
type ProcedureContext = {
path: Procedure[];
next: (procedure: Procedure) => void;
};
type Procedure = {
run: (ctx: ProcedureContext) => unknown;
};
const runProcedure = (
procedure: Procedure,
path: ProcedureContext['path'] = []
) => {
const ctx: ProcedureContext = {
path: [...path, procedure],
next: (procedure) => {
runProcedure(procedure, ctx.path);
},
};
procedure.run(ctx);
};
type IntervalModeOptions = {
mode: 'interval';
duration: number;
};
type TimeoutModeOptions = {
mode: 'timeout';
timeout: number;
};
type EntryOptions = (IntervalModeOptions | TimeoutModeOptions) & {
env?: string;
};
class Entry implements Procedure {
constructor(private options: EntryOptions) {}
run(ctx: ProcedureContext) {
if (this.options.mode === 'interval') {
ctx.next(new Interval(this.options.duration));
} else if (this.options.mode === 'timeout') {
ctx.next(new Timeout(this.options.timeout));
}
}
}
class Interval implements Procedure {
constructor(private duration: number, private i = 0) {}
run(ctx: ProcedureContext) {
console.log('interval', {
i: this.i,
ctx
});
const timeout = new Timeout(this.duration, (ctx) => {
ctx.next(new Interval(this.duration, this.i + 1));
});
ctx.next(timeout);
}
}
class Timeout implements Procedure {
constructor(
private timeout: number,
private timeoutCallback?: Procedure['run']
) {}
run(ctx: ProcedureContext) {
setTimeout(() => {
this.timeoutCallback?.(ctx);
}, this.timeout);
}
}
runProcedure(
new Entry({
mode: 'interval',
duration: 1000,
})
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment