UNPKG

1.96 kBJavaScriptView Raw
1
2//
3// # IperNode
4//
5// A node in an hypergraph.
6//
7
8var _ = require('underscore')
9 , inherits = require('inherits')
10
11var IperElement = require('./IperElement')
12
13function IperNode(graph, opts) {
14 var self = this
15
16 IperElement.call(this, graph)
17
18 if (!_.isObject(opts))
19 opts = {}
20
21 //
22 // ## Attributes
23 //
24
25 //
26 // ### degree
27 //
28 // It is the number of edges incident to the vertex.
29 //
30 // See also [degree on wikipedia](http://en.wikipedia.org/wiki/Degree_(graph_theory)).
31 //
32
33 function getDegree () {
34 var degree = 0
35
36 /* Count occurrences of node id in edge.nodeIds
37 * for every edge in the graph.
38 */
39 _.each(graph.edges, function (edge) {
40 _.each(edge.nodeIds, function (nodeId) {
41 if (nodeId === self.id)
42 degree++
43 })
44 })
45
46 return degree
47 }
48
49 Object.defineProperty(this, 'degree', {get: getDegree})
50
51 //
52 // ### maxDegree
53 //
54
55 function getMaxDegree () {
56 return opts.maxDegree
57 }
58
59 Object.defineProperty(this, 'maxDegree', {get: getMaxDegree})
60
61 /* add this node to graph */
62 graph.nodes.push(this)
63}
64
65inherits(IperNode, IperElement)
66
67//
68// ## Methods
69//
70
71//
72// ### getAdjacentNodeIds()
73//
74
75function getAdjacentNodeIds() {
76 var id = this.id
77
78 var adjacentNodeIds = []
79
80 /* loop over all edges */
81 _.each(this.graph.edges, function (edge) {
82 /* if edge contains node */
83 if (_.contains(edge.nodeIds, id))
84 /* take all nodeIds except node self id */
85 adjacentNodeIds.push(_.without(edge.nodeIds, id))
86 })
87
88 /* since _.without() return an array and nodeIds can be repeated,
89 * use _.uniq() and _.flatten() to return a flat array with no repetition
90 */
91 return _.uniq(_.flatten(adjacentNodeIds))
92}
93
94IperNode.prototype.getAdjacentNodeIds = getAdjacentNodeIds
95
96/* TODO remove(), oppure toglilo ad IperEdge */
97
98module.exports = IperNode
99