UNPKG

nyx_server

Version:

Node内容发布

126 lines (110 loc) 3.27 kB
var _ = require("lodash") function Node(key , parent){ var _children = {}; var _key = key; var _parent = parent; var _data = null; this.addChild = function(key){ if(!this.getNode(key)){ _children[key] = new Node(key , this); } return _children[key]; } this.getNode = function(key){ return _children[key]; } this.getNodeKeys = function(){ return _.keys(_children); } this.setData = function(data){ _data = data; } this.getData = function(){ return _data; } this.toString = function(){ // console.log("key : " , _key); // console.log('data : ' , _data); for(var key in _children){ var node = _children[key]; node.toString(); } } Object.defineProperty(this, "key", {value: _key, writable: true}); Object.defineProperty(this, "parent", {value: _parent, writable: false}); } function TreeStore(nodeDataFactory){ this.root = new Node('root' , null) this.nodeDataFactory = nodeDataFactory; } TreeStore.prototype.addNode = function(path , data){ if(!path){ return this; } var keys = path.split("-"); var _self = this; function _addpath(node , keys , data){ var _key = keys.shift(); node = node.addChild(_key); if(keys.length>0){ _addpath(node , keys , data); }else{ var nodeData = node.getData(); if(!nodeData){ nodeData = _self.nodeDataFactory(data); node.setData(nodeData); return; } nodeData.addData(data); } } _addpath(this.root , keys , data); } /** * 通过路径匹配 * @param {String} path 匹配的路径 * @param {boolean} up 如果up是false则不向上匹配,如过是true则向上匹配, 默认是true */ TreeStore.prototype.matchPath = function(path , up){ up = up || true; if(!path){ return null; } var keys = path.split("-"); function childrenNode(node , keys){ if(keys.length == 0){ return null; } var _key = keys.shift(); var _node = node.getNode(_key); if(!_node && up){ //如果当前节点没子节点并且可以线上匹配,则取上个匹配的节点,u return node; } if(keys.length>0){ return childrenNode(_node , keys); }else{ return _node; } } var matchedNode = childrenNode(this.root , keys); return matchedNode ? matchedNode.getData() : null; } TreeStore.prototype.toString = function(){ this.root.toString(); } module.exports = TreeStore; if(!module.parent){ //for test /* var treeStore = new TreeStore(TempalteNodeDataFactory); treeStore.addNode("A-B-C" , {type:"data" , devices:"all" , data:{a:1}}); treeStore.addNode("D-E-F" , {type:"data1" , devices:"all" , data:{b:2}}); var node = treeStore.matchPath("A-C"); console.log(node.key == "C"); var node = treeStore.matchPath("D-E-F"); console.log(node.key == "F"); var nodeData = node.getData(); var data = nodeData.getData(); console.log(data["data1"]); */ }