Introducing opaque types

This commit is contained in:
maciejhirsz
2018-06-20 17:58:10 +02:00
parent 5658400c67
commit 60f617be66
4 changed files with 22 additions and 7 deletions
+8 -3
View File
@@ -1,21 +1,26 @@
import * as EventEmitter from 'events';
import Node from './node';
import { NodeId } from './nodeId';
export default class Aggregator extends EventEmitter {
private nodes: WeakSet<Node> = new WeakSet;
private nodes: Map<NodeId, Node> = new Map;
private height: number = 0;
add(node: Node) {
this.nodes.add(node);
this.nodes.set(node.id, node);
node.once('disconnect', () => {
node.removeAllListeners('block');
this.nodes.delete(node);
this.nodes.delete(node.id);
});
node.on('block', () => this.updateBlock(node));
}
get nodeList(): Iterable<Node> {
return this.nodes.values();
}
private updateBlock(node: Node) {
if (node.height > this.height) {
this.height = node.height;
+3 -4
View File
@@ -1,14 +1,13 @@
import * as WebSocket from 'ws';
import * as EventEmitter from 'events';
import { Maybe } from './maybe';
import { NodeId, getId } from './nodeId';
import { parseMessage, getBestBlock, Message, BestBlock } from './message';
const BLOCK_TIME_HISTORY = 10;
let idDispenser = 0;
export default class Node extends EventEmitter {
public id: number;
public id: NodeId;
public name: string;
public implementation: string;
public version: string;
@@ -24,7 +23,7 @@ export default class Node extends EventEmitter {
constructor(socket: WebSocket, name: string, config: string, implentation: string, version: string) {
super();
this.id = idDispenser++;
this.id = getId();
this.socket = socket;
this.name = name;
this.config = config;
+9
View File
@@ -0,0 +1,9 @@
import { Opaque } from './opaque';
let currentId = 0;
export type NodeId = Opaque<number, "NodeId">;
export function getId(): NodeId {
return currentId++ as NodeId;
}
+2
View File
@@ -0,0 +1,2 @@
// Hack for Opaque Types
export type Opaque<T, Label> = T & {__TYPE__: Label};