I am facing a challenge with a recursive JSON structure that needs to be stored as a series of maps with keys. The structure comprises flows and subflows that have references to each other. Here are the type declarations, noting that the issue lies in the faulty algorithm:
type Flow = {
flowId: number,
subFlows?: Array<SubFlow>
}
type SubFlow = {
subFlowId: number,
flow?: Flow,
}
type FlowGroup = {
flows: Map<number, Flow>,
subFlows: Map<number, Flow>
}
The end goal is to store the flow within a flowgroup structure using flowIds as keys. Below is an example of the JSON data:
{
"flowId": 90112,
"subFlows": [
{
"subFlowId": 52820,
"flow": {
"flowId": 80032,
"subFlows": [
{
"subFlowId": 76422
},
{
"subFlowId": 12654
}
]
}
},
{
"subFlowId": 12422
}
]
}
However, my attempt at populating this results in an empty flowgroup. Here is the code snippet I used:
const mainFlow:Flow = {
flowId: 90112,
subFlows: _subFlows
}
function processFlow(flow: Flow) {
if (flow && flow.subFlows === undefined) {
flowGroup.flows.set(flow.flowId, flow);
} else if (flow && Array.isArray(flow.subFlows)) {
for (const subFlow of flow.subFlows) {
flowGroup.subFlows.set(subFlow.subFlowId, subFlow);
if (subFlow.flow) {
processFlow(subFlow.flow);
}
}
}
}
processFlow(mainFlow);
console.log(`FlowGroup is ${JSON.stringify(flowGroup)}`);
Here is the data used to create the test scenario:
const subFlow1:SubFlow ={
subFlowId: 52820
}
const subFlow2:SubFlow ={
subFlowId: 12422
}
const flow3:SubFlow = {
subFlowId: 76422
}
const flow4: SubFlow = {
subFlowId: 12654
}
const flow5: Flow = {
flowId: 80032,
subFlows: [flow3, flow4]
}
subFlow1.flow = flow5;
const flowGroup: FlowGroup = {
flows: new Map<number, Flow>(),
subFlows: new Map<number, Flow>()
}
const _subFlows = [subFlow1, subFlow2];
const mainFlow:Flow ={
flowId: 90112,
subFlows: _subFlows
}
Manually printing the values of a map set:
const m = new Map<string, Flow>();
m.set(flow5.flowId, flow5);
for(const [k, v] of m.entries()){
console.log(`Map key = ${k} and value =
${JSON.stringify(v)}`);
}
These are the TypeScript compiler settings used:
"target": "esNext",
"module": "es2022",
"moduleResolution": "node",
Highlighted below is a piece of successful implementation in the application:
productHandler<Product, ProductKey
extends keyof Product>(product: Product, productKey: ProductKey) {
const map = new Map<ProductKey, Array<string>>();
const productData = product[productKey] as unknown as Array<string>;
map.set(productKey, productData)
return map;
}