Skip to content

Instantly share code, notes, and snippets.

@rhogeranacleto
Created June 26, 2024 09:10
Show Gist options
  • Save rhogeranacleto/db5ed23c83eb61cc737fe0c55949aed5 to your computer and use it in GitHub Desktop.
Save rhogeranacleto/db5ed23c83eb61cc737fe0c55949aed5 to your computer and use it in GitHub Desktop.
Tree post and pre execution
interface NodeItem {
cmd?: () => void;
pre?: NodeItem;
post?: NodeItem;
}
const root: NodeItem = {
cmd: () => console.log('just this'),
};
const execute = (node: NodeItem) => {
if (node.pre) {
execute(node.pre);
}
node.cmd?.();
if (node.post) {
execute(node.post);
}
};
const addToTree = (
modifiers: string[],
fn: () => void,
node: Partial<NodeItem>,
) => {
if (modifiers.length === 0) {
node.cmd = fn;
return;
}
const nextModifier = modifiers.pop();
if (nextModifier === '-') {
node.pre ??= {};
addToTree(modifiers, fn, node.pre);
}
if (nextModifier === '+') {
node.post ??= {};
addToTree(modifiers, fn, node.post);
}
};
const build = (cmds: Record<string, () => void>) => {
for (const [cmdName, fn] of Object.entries(cmds).sort(([namea], [nameb]) => {
if (namea.length < nameb.length) return -1;
if (nameb.length < namea.length) return 1;
return 0;
})) {
const modifiers = cmdName.split('run')[0].split('');
addToTree(modifiers, fn, root);
console.log(root);
}
};
const cmds = {
'-run': () => console.log('1'),
run: () => console.log('2'),
'+run': () => console.log('3'),
'+++run': () => console.log('4'),
'+-+run': () => console.log('5'),
'+-run': () => console.log('6'),
};
build(cmds);
execute(root);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment