1 import { isDefined } from "./is-defined"
2 import { isObject } from "./is-object"
3
4 /**
5 * @description
6 * This function is used to flatten nested objects and arrays
7 *
8 * @example
9 *
10 * ```ts
11 * const data = {
12 * root_level_property: "root level",
13 * products: [
14 * {
15 * id: "1",
16 * name: "product 1",
17 * variants: [
18 * { id: "1.1", name: "variant 1.1" },
19 * { id: "1.2", name: "variant 1.2" },
20 * ],
21 * },
22 * {
23 * id: "2",
24 * name: "product 2",
25 * variants: [
26 * { id: "2.1", name: "variant 2.1" },
27 * { id: "2.2", name: "variant 2.2" },
28 * ],
29 * },
30 * ],
31 * }
32 *
33 * const flat = deepFlatMap(
34 * data,
35 * "products.variants",
36 * ({ root_, products, variants }) => {
37 * return {
38 * root_level_property: root_.root_level_property,
39 * product_id: products.id,
40 * product_name: products.name,
41 * variant_id: variants.id,
42 * variant_name: variants.name,
43 * }
44 * }
45 * )
46 * ```
47 */
48
49 export function deepFlatMap(
50 data: any,
51 path: string,
52 callback: (context: Record<string, any>) => any
53 ) {
54 const ROOT_LEVEL = "root_"
55 const keys = path.split(".")
56 keys.unshift(ROOT_LEVEL)
57
58 const lastKey = keys[keys.length - 1]
59 const stack: {
60 element: any
61 path: string[]
62 context: Record<string, any>
63 }[] = [{ element: { [ROOT_LEVEL]: data }, path: keys, context: {} }]
64
65 const results: any[] = []
66 while (stack.length > 0) {
67 const { element, path, context } = stack.shift()!
68 const currentKey = path[0]
69 const remainingPath = path.slice(1)
70
71 if (!isDefined(element?.[currentKey])) {
72 callback({ ...context })
73 continue
74 }
75
76 if (remainingPath.length === 0) {
77 if (Array.isArray(element[currentKey])) {
78 element[currentKey].forEach((item) => {
79 results.push(callback({ ...context, [lastKey]: item }))
80 })
81 } else if (isObject(element[currentKey])) {
82 results.push(callback({ ...context, [lastKey]: element[currentKey] }))
83 }
84 } else {
85 if (Array.isArray(element[currentKey])) {
86 if (element[currentKey].length === 0) {
87 callback({ ...context })
88 continue
89 }
90
91 element[currentKey].forEach((item) => {
92 stack.push({
93 element: item,
94 path: remainingPath,
95 context: { ...context, [currentKey]: item },
96 })
97 })
98 } else if (isObject(element[currentKey])) {
99 stack.push({
100 element: element[currentKey],
101 path: remainingPath,
102 context: { ...context, [currentKey]: element[currentKey] },
103 })
104 }
105 }
106 }
107 return results
108 }