-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathalgorithm.ts
More file actions
115 lines (100 loc) · 2.69 KB
/
algorithm.ts
File metadata and controls
115 lines (100 loc) · 2.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
interface Node {
id: string;
data: {
type: string;
label: string;
message?: string;
buttons?: Button[];
saveResponse?: boolean;
};
type: string;
width?: number;
height?: number;
position?: { x: number; y: number };
positionAbsolute?: { x: number; y: number };
deletable?: boolean;
dragging?: boolean;
selected?: boolean;
}
interface Button {
id: string;
text: string;
type: string;
}
interface Edge {
id: string;
source: string;
target: string;
sourceHandle?: string;
targetHandle?: string;
type?: string;
label?: string;
animated?: boolean;
}
interface SearchCriteria {
button_type?: string;
edge_type?: string;
target_contains?: string;
}
class ChatbotFlowNavigator {
private nodesIndex: Map<string, Node>;
private edgesBySource: Map<string, Edge[]>;
constructor(nodes: Node[], edges: Edge[]) {
// Crear un índice de nodos para acceso O(1)
this.nodesIndex = new Map();
for (const node of nodes) {
this.nodesIndex.set(node.id, node);
}
// Crear un índice de edges por nodo fuente para acceso O(1)
this.edgesBySource = new Map();
for (const edge of edges) {
const source = edge.source;
if (!this.edgesBySource.has(source)) {
this.edgesBySource.set(source, []);
}
this.edgesBySource.get(source)!.push(edge);
}
}
findNextNode(currentNodeId: string, criteria: SearchCriteria): Node | null {
/**
* Encuentra el siguiente nodo basado en criterios específicos
* Complejidad: O(k) donde k es el número de edges del nodo actual
*/
// Obtener todos los edges que salen del nodo actual
const outgoingEdges = this.edgesBySource.get(currentNodeId) || [];
if (outgoingEdges.length === 0) {
return null;
}
// Aplicar criterios de búsqueda
for (const edge of outgoingEdges) {
if (this.matchesCriteria(edge, criteria)) {
const targetNodeId = edge.target;
return this.nodesIndex.get(targetNodeId) || null;
}
}
return null;
}
private matchesCriteria(edge: Edge, criteria: SearchCriteria): boolean {
/**
* Evalúa si un edge cumple con los criterios dados
*/
// Ejemplo de criterios basados en tu estructura
if (criteria.button_type) {
if (edge.sourceHandle && edge.sourceHandle.includes(criteria.button_type)) {
return true;
}
}
if (criteria.edge_type) {
if (edge.type === criteria.edge_type) {
return true;
}
}
if (criteria.target_contains) {
if (edge.target && edge.target.includes(criteria.target_contains)) {
return true;
}
}
return false;
}
}
export { ChatbotFlowNavigator, Node, Edge, SearchCriteria };