Skip to content

Instantly share code, notes, and snippets.

@kva1966
Last active July 28, 2017 07:47
Show Gist options
  • Save kva1966/afbc79aee329712538374419d9a60955 to your computer and use it in GitHub Desktop.
Save kva1966/afbc79aee329712538374419d9a60955 to your computer and use it in GitHub Desktop.
TypeScript Interesting Tidbits, e.g. Index Types!
// Quick, simple enums -- typechecked!
type TraversalOrder = "inorder" | "preorder" | "postorder";
type NodePosition = "root" | "left" | "right";
// Of course TypeScript has proper enums, but this might be a good way of
// doing interop without writing wrapper types.
// Type Aliases for complex function types
type VisitorFn<T, N extends Node<T>> = (node: N, depth: number, position: NodePosition) => void;
type TraversalFn<T> = (node: BstNode<T>, depth: number, position: NodePosition) => void;
// Forward Referencing of type BinarySearchTreeNode, yay!
// Will be used to demonstrate index types soon.
interface NodePointers<T> {
parent: BinarySearchTreeNode<T>;
left: BinarySearchTreeNode<T>;
right: BinarySearchTreeNode<T>;
}
// Note that it implements NodePointers above.
class BinarySearchTreeNode<T> implements Node<T>, NodePointers<T> {
key: T;
parent: BinarySearchTreeNode<T>;
left: BinarySearchTreeNode<T>;
right: BinarySearchTreeNode<T>;
// <snip>
}
class BinarySearchTree<T> {
private root: BstNode<T> = null;
// ...
//
// Index Types in Action -- look at _add() calling linkNode()
//
private _add(node: BstNode<T>, key: T): BstNode<T> {
if (key < node.key) {
if (node.left === null) {
return this.linkNode(node, "left", key);
} else {
return this._add(node.left, key);
}
} else {
if (node.right === null) {
return this.linkNode(node, "right", key);
} else {
return this._add(node.right, key);
}
}
}
// P is constrained to properties of NodePointers: parent, left, right
// strings are passed in for property names -- but they are typechecked to only meet the above literals.
private linkNode<P extends keyof NodePointers<T>>(node: BstNode<T>, prop: P, key: T): BstNode<T> {
let newNode: BstNode<T> = new BinarySearchTreeNode<T>(key);
newNode.parent = node;
node[prop] = newNode;
return newNode;
}
// ...
}
// Inline, Anonymous Typing - Array of anonymous type with node and offset.
let drawnNodes: { node: BstNodeData<T>; offset: NodeOffset }[] = [];
// then push anonymous objects matching type.
drawnNodes.push({ node: someNode, offset: someOffset});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment