Skip to content

Instantly share code, notes, and snippets.

@xandout
Created March 28, 2015 03:45
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 xandout/6f65a5a6888bbfbeffa2 to your computer and use it in GitHub Desktop.
Save xandout/6f65a5a6888bbfbeffa2 to your computer and use it in GitHub Desktop.
Simple L2 Switch Implementation
var switchport = function(vlan){
this.vlan = vlan;
this.attach = function(device){
this.device = device.mac;
}
}
var vlan = function(vlanid, ipaddress){
this.vlanid = vlanid;
this.ipaddress = ipaddress || null;
}
var jswitch = function(name, portcount){
this.name = name;
this.portcount = portcount;
this.ports = [];
this.addPort = function(switchport){
if(this.ports.length == portcount){
throw "Port Count Exceeded";
} else {
this.ports.push(switchport);
return 1;
}
}
this.showMacTable = function(port){
if(port){
return this.ports[port].device;
}
var maclist = [];
for(var p in this.ports){
if(this.ports[p].device){
maclist.push({'port':p, 'mac':this.ports[p].device});
}
}
return maclist;
}
}
var device = function(name, mac){
return {'name':name, 'mac':mac};
}
var js = new jswitch('test', 4);
js.addPort(new switchport(new vlan(32)));
js.addPort(new switchport(new vlan(1)));
js.addPort(new switchport(new vlan(34)));
js.addPort(new switchport(new vlan(1)));
console.log(js.name, ' has ', js.ports.length, ' of ', js.portcount, ' ports inserted');
var d = new device('mitch', '1234');
js.ports[0].attach(d);
js.ports[2].attach(new device('ash', '4567'));
console.log(js.showMacTable());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment