-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathEventTreeNode.js
84 lines (79 loc) · 2.82 KB
/
EventTreeNode.js
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
const Event = require('./Event.js');
class EventTreeNode {
constructor(event, depth) {
if (event === null || event === undefined) {
throw 'Cannot create EventNode with null or undefined';
}
if (!(event instanceof Event)) {
throw 'Wrong Type, should be Event';
}
if (isNaN(depth)) {
throw 'Cannot create EventNode with no depth';
}
if (depth < 0 ) {
throw 'depth should be positive';
}
this.event = event;
this.key = event.key;
this.depth = depth;
this.occurrence = 0;
if (depth > 1) {
this.children = new Map();
}
}
learn(eventList) {
if (this.depth == 0) {
return;
}
if (eventList === null || eventList === undefined || eventList.length === 0) {
return;
}
let lastEvent = eventList[eventList.length - 1];
if (lastEvent.key !== this.key) {
throw 'Cannot learn, different event';
}
this.occurrence++;
let subEventList = eventList.slice(0, eventList.length - 1);
if (this.depth > 1 && subEventList.length >= 1) {
let lastOfSubEvent = subEventList[subEventList.length - 1];
let childTreeNode = this.children.get(lastOfSubEvent.key);
if (childTreeNode === undefined) {
childTreeNode = new EventTreeNode(lastOfSubEvent, this.depth-1);
this.children.set(lastOfSubEvent.key, childTreeNode);
}
childTreeNode.learn(subEventList);
}
}
getOccurence(sequence) {
if (! Array.isArray(sequence)) {
throw 'sequence should be an array of event (not an array)';
}
if (sequence.length < 1) {
throw 'sequence should at least contain one event';
}
let lastEvent = sequence[sequence.length - 1];
if (! (lastEvent instanceof Event)) {
throw 'sequence should be an array of event (wrong type)';
}
if (lastEvent.key !== this.key) {
return 0;
}
if (sequence.length === 1) {
return this.occurrence;
} else {
if (this.depth > 1) {
let subSequence = sequence.slice(0, sequence.length - 1);
let lastOfSubSequence = subSequence[subSequence.length -1];
let subTreeNode = this.children.get(lastOfSubSequence.key);
if (subTreeNode === undefined) {
return 0;
} else {
return subTreeNode.getOccurence(subSequence);
}
} else {
return 0;
}
}
}
}
module.exports = EventTreeNode;