-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.js
More file actions
85 lines (67 loc) · 1.94 KB
/
Copy pathindex.js
File metadata and controls
85 lines (67 loc) · 1.94 KB
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
85
/**
* Evented version of a graph
*
* @module evented-graph
*/
var Graph = require('tolstoy');
var Emitter = require('events').EventEmitter;
var inherits = require('inherits');
var extend = require('xtend/mutable');
function EventedGraph (arg) {
if (!(this instanceof EventedGraph)) return new EventedGraph(arg);
Emitter.call(this);
//constructor doesn’t check type of this
Graph.prototype.constructor.call(this, arg);
};
/**
* Add inheritance — being an emitter is more important than being a graph,
* as it is supposed that evented-graph
* is the highest possible graph structure per-project
* you normally never check EventedGraph instanceof Graph.
*/
inherits(EventedGraph, Emitter);
extend(EventedGraph.prototype, Graph.prototype);
EventedGraph.prototype.off = function () {
if (arguments.length > 1) {
Emitter.prototype.removeListener.apply(this, arguments);
} else {
Emitter.prototype.removeAllListeners.apply(this, arguments);
}
};
/**
* Redefine mutator methods
*/
'clear add delete'.split(' ').forEach(function (methName) {
var pureMeth = Graph.prototype[methName];
EventedGraph.prototype[methName] = function (a) {
var prev = this.nodes.size;
var res = pureMeth.call(this, a);
if (this.nodes.size !== prev) {
this.emit.call(this, methName, a);
this.emit('change');
}
return res;
};
});
'connect disconnect'.split(' ').forEach(function (methName) {
var pureMeth = Graph.prototype[methName];
EventedGraph.prototype[methName] = function (a, b) {
if (!this.nodes.has(a)) {
return pureMeth.call(this, a, b);
}
var prev = this.edges.get(a).size;
if (arguments.length < 2) {
this.outputs.get(a).forEach(function (b) {
this.disconnect(a, b);
}, this);
return this.edges.get(a).size !== prev;
}
var res = pureMeth.call(this, a, b);
if (this.edges.get(a).size !== prev) {
this.emit.call(this, methName, a, b);
this.emit('change');
}
return res;
};
});
module.exports = EventedGraph;