Skip to content

Commit

Permalink
refactor: refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
lisez committed May 27, 2024
1 parent 203d258 commit de9515e
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 21 deletions.
42 changes: 21 additions & 21 deletions modules/runners/sequence.ts
Original file line number Diff line number Diff line change
@@ -1,45 +1,45 @@
import type { EventHandlerSignature } from "modules/types.ts";

import { SingleRunner } from "modules/runners/single.ts";

/**
* Run handlers in sequence.
*/
export class SequenceRunner {
export class SequenceRunner<
T extends EventHandlerSignature<any> = EventHandlerSignature<any>,
> {
/**
* Create a new instance of the SequenceRunner.
* @param handlers The handlers to run.
*/
constructor(private handlers: EventHandlerSignature<any>[]) {
constructor(private handlers: T[]) {
this.handlers = handlers;
}

/**
* Wait for the handler to finish before moving to the next handler.
* @param pointer The current handler index.
* @param profile The handler profile.
* @param args The arguments to pass to the handlers.
*/
private asyncExec(
pointer: number,
profile: EventHandlerSignature<any>,
...args: any[]
): Promise<void> {
return Promise.resolve(profile.handler(...args)).then(() =>
this.exec(pointer + 1, ...args)
);
}

/**
* Execute the handlers in sequence.
* @param pointer The current handler index.
* @param args The arguments to pass to the handlers.
*/
exec(pointer: number = 0, ...args: any[]): void | Promise<void> {
exec(
pointer: number = 0,
...args: Parameters<T["handler"]>
): void | Promise<void> {
const profile = this.handlers[pointer];
if (!profile) return;

const result = new SingleRunner<T>(profile).exec(
...args,
);

/**
* Wait for the handler to finish before moving to the next handler.
*/
if (profile.options?.async) {
return this.asyncExec(pointer, profile, ...args);
return Promise.resolve(result).then(() =>
this.exec(pointer + 1, ...args)
);
}
profile.handler(...args);
return this.exec(pointer + 1, ...args);
}
}
33 changes: 33 additions & 0 deletions modules/runners/single.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { EventHandlerSignature } from "modules/types.ts";

/**
* The result of a single runner.
*/
export type SingleRunnerResult<T extends (...args: any[]) => any> = ReturnType<
T
>;

/**
* Run a handler.
*/
export class SingleRunner<
T extends EventHandlerSignature<any> = EventHandlerSignature<any>,
> {
/**
* Create a new instance of the SingleRunner.
* @param profile The handler profile.
*/
constructor(private profile: T) {
this.profile = profile;
}

/**
* Execute the handler.
* @param args The arguments to pass to the handler.
*/
exec(
...args: Parameters<T["handler"]>
): SingleRunnerResult<T["handler"]> {
return this.profile.handler(...args);
}
}

0 comments on commit de9515e

Please sign in to comment.