Created
September 7, 2022 16:42
-
-
Save CapsAdmin/e1c12bb9e24b9a0d0095cc57aba5000c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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