|
|
|
|
|
by SirensOfTitan
1128 days ago
|
|
One control flow function I use often in JavaScript is my `runIfUnhandled` function: export const UNHANDLED: unique symbol = Symbol("UNHANDLED");
export function runIfUnhandled<TReturn = void>(
ifUnhandled: () => TReturn,
run: (unhandled: Unhandled) => TReturn | Unhandled,
): TReturn {
const runResult = run(UNHANDLED);
if (runResult === UNHANDLED) {
return ifUnhandled();
}
return runResult;
}
I often use it to use guards to bail early, while keeping the default path dry. In particular, I used it heavily in a custom editor I built for a prior project, example: runIfUnhandled(
() => serialize(node, format),
(UNHANDLED) => {
if (
!Element.isElement(node) ||
!queries.isBlockquoteElement(node)
) {
return UNHANDLED;
}
switch (format) {
case EditorDocumentFormat.Markdown: {
const serialized = serialize(node, format) as string;
return `> ${serialized}`;
}
default: {
return UNHANDLED;
}
}
},
);
|
|