jasc
Version:
Jasc Another Service Container
80 lines (79 loc) • 3.28 kB
JavaScript
;
var __read = (this && this.__read) || function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
};
var __spread = (this && this.__spread) || function () {
for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i]));
return ar;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createTree = exports.createNode = void 0;
var _traverseChildren = function (cb, node, depth) {
if (depth === void 0) { depth = 0; }
var res = cb(node, depth);
return typeof res === 'boolean' && res
|| __spread(node.children).some(function (n) { return _traverseChildren(cb, n, depth + 1); });
};
var _traverseParents = function (cb, node) {
var res = cb(node);
return typeof res === 'boolean' && res
|| __spread(node.parents).some(function (p) { return _traverseParents(cb, p); });
};
var createNode = function (key, parents, value) {
var node = {
key: key, value: value,
parents: new Set(parents), children: new Set(),
traverseChildren: function (cb, depth) {
if (depth === void 0) { depth = 0; }
return _traverseChildren(cb, this, depth);
},
traverseParents: function (cb) { return __spread(this.parents).some(function (parent) { return _traverseParents(cb, parent); }); }
};
parents.forEach(function (parent) { return parent.children.add(node); });
return node;
};
exports.createNode = createNode;
var createTree = function () {
var nodes = {};
return {
get: function (key) { return nodes[key]; },
has: function (key) { return nodes.hasOwnProperty(key); },
getRoots: function () { return Object.values(nodes).filter(function (node) { return node.parents.size === 0; }); },
add: function (key, parent, value) {
if (this.has(key))
throw new Error("Can't redefine property " + key);
parent = parent || [];
var parents = Array.isArray(parent) ? parent : [parent];
return nodes[key] = exports.createNode(key, parents, value);
},
traverseRoots: function (cb) {
return this
.getRoots()
.some(function (root) { return root.traverseChildren(cb); });
},
dump: function () {
this.traverseRoots(function (node, depth) {
if (depth === 0) {
console.log("\u250C " + node.key + " \u221A\u1D3F\u1D3C\u1D3C\u1D40");
return;
}
console.log("\u251C" + '─'.repeat(depth > 1 ? depth - 2 : 0) + (depth > 1 ? '└' : '') + (node.children.size > 0 ? '┬' : '─') + " " + node.key);
});
return this;
}
};
};
exports.createTree = createTree;