@gram-data/gram-ops
Version:
gram data graph operations
70 lines (62 loc) • 2.12 kB
JavaScript
;
Object.defineProperty(exports, '__esModule', { value: true });
var gramAst = require('@gram-data/gram-ast');
var gramBuilder = require('@gram-data/gram-builder');
var count = function count(p) {
return p.children.reduce(function (acc, child) {
return acc + count(child);
}, 1);
};
var head = function head(p) {
return p.children === undefined || p.children.length === 0 ? p : head(p.children[0]);
};
var tail = function tail(p) {
return p.children === undefined || p.children.length === 0 ? p : tail(p.children[p.children.length - 1]);
};
var merge = function merge(_, next) {
// return path
return next;
};
var identity = function identity(p) {
return p.id;
};
/**
* Node set projected from within a path.
*
* @param p paths from which to project nodes
*/
var nodes = function nodes(p) {
if (gramAst.isGramNode(p)) return [p];
if (gramAst.isGramSeq(p)) return nodes(p.children);
if (Array.isArray(p)) {
var unidentifiedNodes = [];
var nodemap = p.map(nodes).flat().reduce(function (acc, child) {
if (child.id) {
if (acc.has(child.id)) {
acc.set(child.id, Object.assign(acc.get(child.id), child));
} else {
acc.set(child.id, child);
}
} else {
unidentifiedNodes.push(child);
}
return acc;
}, new Map());
return Array.from(nodemap.values()).concat(unidentifiedNodes);
} else {
return nodes(p.children);
}
};
var edges = function edges(p) {
return p === undefined ? [] : p.children === undefined || p.children.length === 0 ? [] : p.children.length === 2 ? [].concat(edges(p.children[0]), p.kind !== undefined && p.kind !== 'pair' ? [gramBuilder.edge([tail(p.children[0]), head(p.children[1])], p.kind, p.id, p.labels, p.record)] : [], edges(p.children[1])) : p.children.reduce(function (acc, child) {
return [].concat(acc, edges(child));
}, []);
};
exports.count = count;
exports.edges = edges;
exports.head = head;
exports.identity = identity;
exports.merge = merge;
exports.nodes = nodes;
exports.tail = tail;
//# sourceMappingURL=gram-ops.cjs.development.js.map