Skip to content

Instantly share code, notes, and snippets.

@CapsAdmin
Created September 7, 2022 16:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CapsAdmin/e1c12bb9e24b9a0d0095cc57aba5000c to your computer and use it in GitHub Desktop.
Save CapsAdmin/e1c12bb9e24b9a0d0095cc57aba5000c to your computer and use it in GitHub Desktop.
type Mode = "safe" | "faster";
const modeStack: Mode[] = ["safe"];
const getMode = () => modeStack[0];
const pushMode = (mode: Mode) => modeStack.unshift(mode);
const popMode = () => modeStack.shift();
type HasLength = { length: number };
type WithModeRequest<Result> = {
mode: Mode;
action: () => Result;
};
function reallyPerform<Task extends HasLength>(task: Task): number {
console.log(`${getMode()}: ${task}`);
return task.length;
}
function perform<Task extends HasLength>(task: Task): number {
return reallyPerform(task);
}
function withMode<Result>(request: WithModeRequest<Result>): Result {
try {
pushMode(request.mode);
return request.action();
} finally {
popMode();
}
}
export function main() {
console.log(
perform("something"),
withMode({ mode: "faster", action: () => perform("reliable") }),
perform(["again"])
);
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment