Skip to content

Instantly share code, notes, and snippets.

@BRonen
Created January 4, 2024 01:23
Show Gist options
  • Save BRonen/a709dc80d83d72072962331be4f324f6 to your computer and use it in GitHub Desktop.
Save BRonen/a709dc80d83d72072962331be4f324f6 to your computer and use it in GitHub Desktop.
Brief example about binary trees made in typescript
const useState = <A>(a: any): any => { };
type Tree = [number, Tree, Tree] | null
type UUID = string;
type Edge = { from: UUID, to: UUID }
type NNode = { nodes: NNode[], id: UUID, label: string }
const [nodes, setNodes] = useState<NNode | null>(null);
const root: NNode = {
id: 'uuid 1',
label: 'john doe',
nodes: [
],
};
setNodes(root);
const addNewNodes = (nodes: NNode[], id: string, newNodes: NNode[]): NNode[] => {
const target = nodes.find(node => node.id === id);
if(!target)
return nodes.map(children => (
{...children, nodes: addNewNodes(children.nodes, id, newNodes)}
));
return [
...nodes.filter(node => node.id === id),
{
...target,
nodes: newNodes
}
];
};
const id: string = 'uuid 1';
let newNodes: NNode[];
setNodes(state => addNewNodes(state.nodes, id, newNodes))
const y1: Tree = [5, null, null]
const y: Tree = [4, y1, null]
const x1: Tree = [3, null, null]
const x: Tree = [2, x1, null]
const t: Tree = [1, x, y]
const navigate = (tree: Tree, mov: (1 | 0)[]): Tree => {
if (tree === null) return null;
if (mov.length === 0) return tree;
const [i, ...rest] = mov;
if (i === 1)
return navigate(tree[1], rest);
return navigate(tree[2], rest)
};
console.log(navigate(t, [0]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment