@visactor/vgrammar-hierarchy
Version:
Layout of hierarchical data for VGrammar
48 lines (45 loc) • 2.32 kB
JavaScript
import { isNil, toValidNumber } from "@visactor/vutils";
export const calculateNodeValue = (subTree, output, depth = 0, flattenIndex = -1, parent, getNodeKey, valueField = "value") => {
let sum = 0, prevFlattenIndex = null != flattenIndex ? flattenIndex : -1, maxDepth = depth;
return subTree.forEach(((datum, index) => {
var _a, _b;
const node = {
flattenIndex: ++prevFlattenIndex,
key: getNodeKey ? getNodeKey(datum) : `${null !== (_a = null == parent ? void 0 : parent.key) && void 0 !== _a ? _a : ""}-${index}`,
maxDepth: -1,
depth: depth,
index: index,
value: datum[valueField],
isLeaf: !0,
datum: parent ? parent.datum.concat(datum) : [ datum ],
parentKey: null == parent ? void 0 : parent.key
};
if (null === (_b = datum.children) || void 0 === _b ? void 0 : _b.length) {
node.children = [], node.isLeaf = !1;
const res = calculateNodeValue(datum.children, node.children, depth + 1, prevFlattenIndex, node, getNodeKey, valueField);
node.value = isNil(datum[valueField]) ? res.sum : Math.max(res.sum, toValidNumber(datum[valueField])),
prevFlattenIndex = res.flattenIndex, maxDepth = Math.max(res.maxDepth, maxDepth);
} else node.isLeaf = !0, node.value = toValidNumber(datum[valueField]);
sum += Math.abs(node.value), output.push(node);
})), {
sum: sum,
maxDepth: maxDepth,
flattenIndex: prevFlattenIndex
};
};
export const eachBefore = (subTree, callback, parent, ctx) => {
let ctxRes = ctx;
return subTree.forEach(((node, index) => {
var _a;
ctxRes = callback(node, index, parent, ctxRes), (null === (_a = node.children) || void 0 === _a ? void 0 : _a.length) && (ctxRes = eachBefore(node.children, callback, node, ctxRes));
})), ctx;
};
export const eachAfter = (subTree, callback, parent, ctx) => {
let ctxRes = ctx;
return subTree.forEach(((node, index) => {
var _a;
(null === (_a = node.children) || void 0 === _a ? void 0 : _a.length) && (ctxRes = eachAfter(node.children, callback, node, ctxRes)),
ctxRes = callback(node, index, parent, ctxRes);
})), ctxRes;
};
//# sourceMappingURL=utils.js.map