Created
September 25, 2018 18:09
-
-
Save davidapple/d831fe880222eb74599faff013081576 to your computer and use it in GitHub Desktop.
Graph data structure using Backbone for js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/***************************************************** | |
* Class: Graph. Data Structures in JS, Feb 2016 | |
* Anatol Marezhanyi http://linkedin.com/in/merezhany/ | |
* Class: BackboneGraph. Sep 2018 | |
* Developed for BackboneJS by David Apple | |
*****************************************************/ | |
'use strict' | |
class BackboneGraph { | |
constructor() { | |
this.Node = Backbone.Model.extend() | |
this.Nodes = Backbone.Collection.extend({ | |
model: Node | |
}) | |
this.nodes = new this.Nodes | |
} | |
addNode(data) { | |
this.nodes.add(new this.Node(_.extend({ | |
type: 'node' | |
}, data))) | |
} | |
removeNode(name) { | |
this.nodes.remove(this.nodes.where({name: name})) | |
this.nodes.remove(this.nodes.where({from: name})) | |
this.nodes.remove(this.nodes.where({to: name})) | |
} | |
hasNode(name) { | |
return !!this.nodes.findWhere({name: name}) | |
} | |
addEdge(nodeFrom, nodeTo) { | |
if (this.hasNode(nodeFrom) && this.hasNode(nodeTo)) { | |
this.addNode({ | |
type: 'edge', | |
from: nodeFrom, | |
to: nodeTo | |
}) | |
} | |
} | |
removeEdge(nodeFrom, nodeTo) { | |
if (this.hasNode(nodeFrom) && this.hasNode(nodeTo)) { | |
this.nodes.remove(this.nodes.where({from: nodeFrom, to: nodeTo})) | |
} | |
} | |
hasEdge(nodeFrom, nodeTo) { | |
return !!this.nodes.findWhere({from: nodeFrom, to: nodeTo}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment