PromucFlow_constructor/app/client/src/utils/treeUtils.ts

36 lines
889 B
TypeScript
Raw Normal View History

2019-11-19 12:44:58 +00:00
type Tree = {
children?: Tree[];
[key: string]: any;
};
export const traverseTree = (tree: Tree, callback: (tree: Tree) => void) => {
2019-11-19 12:44:58 +00:00
callback(tree);
if (tree.children) {
2020-12-24 04:32:25 +00:00
tree.children.forEach((b) => traverseTree(b, callback));
2019-11-19 12:44:58 +00:00
}
};
export const mapTree = (tree: Tree, callback: (tree: Tree) => Tree) => {
2019-11-19 12:44:58 +00:00
const mapped = callback(tree);
if (tree.children && tree.children.length) {
2020-12-24 04:32:25 +00:00
const children: Tree[] = tree.children.map((branch) =>
2019-11-19 12:44:58 +00:00
mapTree(branch, callback),
);
return { ...mapped, children };
}
return { ...mapped };
};
/**
* This function sorts the object's value which is array of string.
*
* @param {Record<string, Array<string>>} data
* @return {*}
*/
export const sortObjectWithArray = (data: Record<string, Array<string>>) => {
Object.entries(data).map(([key, value]) => {
data[key] = value.sort();
});
return data;
};