1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768 |
- import _ from "lodash";
- export const s3ContentsToTree = (
- s3Contents,
- props = {},
- reducer: (...args: unknown[]) => Record<string, unknown> = () => ({})
- ) => {
- let __result = [];
- let level = { __result, __prefix: "" };
- props = Object.assign(
- {
- key: "key",
- label: "label",
- children: "children",
- },
- props
- );
- s3Contents.forEach((s3Content) => {
- s3Content.Key.split("/").reduce((r, label, i, a) => {
- if (!r[label]) {
- const __prefix = `${r.__prefix ? r.__prefix + "/" : ""}${label}`;
- r[label] = { __result: [], __prefix };
- r.__result.push({
- [props.key]: __prefix,
- [props.label]: label,
- [props.children]: r[label].__result,
- // NOTE 这里要小心覆盖掉props.key props.label props.children
- ...reducer(r, label, i, a, s3Content),
- });
- }
- return r[label];
- }, level);
- });
- return __result;
- };
- export const trimTreeForSideBar = (tree) => {};
- type TreeNodeLike = {
- label?: string;
- children?: TreeNodeLike[];
- __path__?: string[];
- } & { [K: string]: unknown };
- export const getTreeFlatten = <T extends TreeNodeLike>(
- treeNode: T,
- order: "preorder" | "postorder" = "preorder",
- mode: "all" | "leaf" = "leaf",
- path: string[] = []
- ): (T & TreeNodeLike)[] => {
- treeNode.__path__ = [...path, treeNode.label ?? ""];
- if (treeNode.children?.length) {
- const result = _.flatMap<T, T>(treeNode.children as T[], (node) =>
- getTreeFlatten(node, order, mode, treeNode.__path__)
- );
- if (mode === "all") {
- if (order === "preorder") {
- result.unshift(treeNode);
- } else if (order === "postorder") {
- result.push(treeNode);
- }
- }
- return result;
- }
- return [treeNode];
- };
|