landers.angular
Version:
landers.angular
74 lines (61 loc) • 2.35 kB
JavaScript
;angular.module('Landers.angular')
.factory('TreeJson', [function(){
var TreeJson = function(data){
this.data = data;
this.keys = {
'id': 'key',
'childs': 'subs'
};
var that = this;
function findIndex(array, key){
var id = that.keys.id;
var index = array.findIndex(function(item, index, arr){
return item[id] == key
});
if ( isNaN(index) ) {
throw '未找到标识为' + key + '的分支';
}
return array[index];
};
this.setKeys = function(id, childs){
if ( id ) that.keys.id = id;
if ( childs ) that.keys.childs = childs;
};
this.getByKeys = function(keys, key){
var data = that.data;
var childs = that.keys.childs;
var nodes = [];
var keys_left = keys.slice(0, keys.length-1);
var last_key = keys[keys.length-1];
if ( keys_left.length ) {
keys_left.map(function(_key){
var json = findIndex(data, _key);
var json_clone = angular.extend({}, json);
delete json_clone[childs];
nodes.push( key ? json_clone[key] : json_clone);
data = json[childs];
});
}
var dat = findIndex(data, last_key);
nodes.push( key ? dat[key] : dat);
return nodes;
};
this.getByIndexs = function(indexs){
var obj = that.data;
var id = that.keys.id;
var childs = that.keys.childs;
indexs.map(function(index){
obj = obj[index][childs];
});
return obj;
};
this.find = function(keys, key){
var nodes = that.get(keys);
var last_node = nodes[nodes.length-1];
return key ? last_node[key] : last_node;
};
};
return {
make:function(data){return new TreeJson(data);},
};
}]);