@gram-data/gram-ops
Version:
gram data graph operations
60 lines (54 loc) • 1.91 kB
JavaScript
import { isGramNode, isGramSeq } from '@gram-data/gram-ast';
import { edge } from '@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 (isGramNode(p)) return [p];
if (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' ? [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));
}, []);
};
export { count, edges, head, identity, merge, nodes, tail };
//# sourceMappingURL=gram-ops.esm.js.map