pitaya-launcher/src/util/tree.js

74 lines
1.6 KiB
JavaScript
Raw Normal View History

2015-09-17 12:04:33 +02:00
var _ = require('lodash');
2015-11-03 17:45:37 +01:00
var update = require('react-addons-update');
var RecursiveIterator = require('recursive-iterator');
2015-09-17 12:04:33 +02:00
2015-11-03 17:45:37 +01:00
function Tree(srcState) {
this._keyCount = 0;
this._state = srcState || {};
}
2015-09-17 12:04:33 +02:00
2015-11-03 17:45:37 +01:00
var p = Tree.prototype;
2015-09-17 12:04:33 +02:00
2015-11-03 17:45:37 +01:00
p.get = function(pathArr) {
var obj = this._state;
for(var i = 0, len = pathArr.length; i < len; ++i) {
obj = obj[pathArr[i]];
if(!obj) throw new Error('Unexistant tree path: "'+pathArr.join('.')+'"');
2015-09-17 12:04:33 +02:00
}
2015-11-03 17:45:37 +01:00
return obj;
2015-09-17 12:04:33 +02:00
};
2015-11-03 17:45:37 +01:00
p.update = function(pathArr, updateCommands) {
var updateQuery = this._createUpdateQueryForPath(pathArr, updateCommands);
this._state = update(this._state, updateQuery);
return this;
};
2015-09-17 12:04:33 +02:00
2015-11-03 17:45:37 +01:00
p.del = function(pathArr) {
var prop = pathArr[pathArr.length-1];
var parentPath = pathArr.slice(0, -1);
this.update(parentPath, {
"$apply": function(item) {
delete item[prop];
return item;
2015-09-17 12:04:33 +02:00
}
});
2015-11-03 17:45:37 +01:00
return this;
2015-09-17 12:04:33 +02:00
};
2015-11-03 17:45:37 +01:00
p.find = function(obj) {
var iterator = this._getStateIterator();
for(var item = iterator.next(); !item.done; item = iterator.next()) {
var state = item.value;
if(state.node === obj) {
return state;
}
}
};
2015-09-17 12:04:33 +02:00
2015-11-03 17:45:37 +01:00
p.getState = function() {
return this._state;
};
2015-09-17 12:04:33 +02:00
2015-11-03 17:45:37 +01:00
p.toJSON = function() {
return this._state;
};
2015-09-17 12:04:33 +02:00
2015-11-03 17:45:37 +01:00
p._getStateIterator = function() {
var iterator = new RecursiveIterator(this._state);
return iterator;
};
2015-09-17 12:04:33 +02:00
2015-11-03 17:45:37 +01:00
p._createUpdateQueryForPath = function(pathArr, updateCommands) {
var cursor, query = {};
cursor = query;
for(var i = 0, len = pathArr.length; i < len-1; ++i) {
cursor = cursor[pathArr[i]] = {};
}
cursor[pathArr[pathArr.length-1]] = updateCommands;
return query;
2015-09-17 12:04:33 +02:00
};
2015-11-03 17:45:37 +01:00
module.exports = Tree;