Skip to content

Instantly share code, notes, and snippets.

@davidapple
Created September 25, 2018 18:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidapple/d831fe880222eb74599faff013081576 to your computer and use it in GitHub Desktop.
Save davidapple/d831fe880222eb74599faff013081576 to your computer and use it in GitHub Desktop.
Graph data structure using Backbone for js
/*****************************************************
* 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