summaryrefslogtreecommitdiff
path: root/src/prelude/tree.ts
blob: 519234a0b0a05f69681c1163f7f2cb87c75ca483 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import { concat, sum } from './array';

export type Tree<T> = {
	node: T,
	children: Forest<T>;
};

export type Forest<T> = Tree<T>[];

export function createLeaf<T>(node: T): Tree<T> {
	return { node, children: [] };
}

export function createTree<T>(node: T, children: Forest<T>): Tree<T> {
	return { node, children };
}

export function hasChildren<T>(t: Tree<T>): boolean {
	return t.children.length !== 0;
}

export function preorder<T>(t: Tree<T>): T[] {
	return [t.node, ...preorderF(t.children)];
}

export function preorderF<T>(ts: Forest<T>): T[] {
	return concat(ts.map(preorder));
}

export function countNodes<T>(t: Tree<T>): number {
	return preorder(t).length;
}

export function countNodesF<T>(ts: Forest<T>): number {
	return sum(ts.map(countNodes));
}