-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvisualizer.js
More file actions
88 lines (71 loc) · 2.18 KB
/
Copy pathvisualizer.js
File metadata and controls
88 lines (71 loc) · 2.18 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
export class ArrayVisualizer {
constructor(container) {
this.container = container;
this.array = [];
this.bars = [];
}
setArray(arr) {
this.array = [...arr];
this.render();
}
updateArray(arr) {
this.array = [...arr];
this.updateBars();
}
render() {
this.container.innerHTML = '';
this.bars = [];
if (this.array.length === 0) {
this.container.innerHTML = '<div style="color: #cbd5e1; font-size: 1.2rem;">Enter an array to visualize</div>';
return;
}
const maxValue = Math.max(...this.array);
const minValue = Math.min(...this.array);
const range = maxValue - minValue || 1;
this.array.forEach((value, index) => {
const bar = document.createElement('div');
bar.className = 'array-bar';
// Calculate height (minimum 30px, maximum 280px)
const height = Math.max(30, (value - minValue) / range * 250 + 30);
bar.style.height = `${height}px`;
// Add value label
const label = document.createElement('span');
label.textContent = value;
bar.appendChild(label);
this.container.appendChild(bar);
this.bars.push(bar);
});
}
updateBars() {
if (this.bars.length !== this.array.length) {
this.render();
return;
}
const maxValue = Math.max(...this.array);
const minValue = Math.min(...this.array);
const range = maxValue - minValue || 1;
this.array.forEach((value, index) => {
const bar = this.bars[index];
const height = Math.max(30, (value - minValue) / range * 250 + 30);
bar.style.height = `${height}px`;
bar.querySelector('span').textContent = value;
});
}
highlightBars(indices, className) {
this.clearHighlights();
indices.forEach(index => {
if (index >= 0 && index < this.bars.length) {
this.bars[index].classList.add(className);
}
});
}
clearHighlights() {
this.bars.forEach(bar => {
bar.classList.remove('comparing', 'swapping', 'sorted', 'found');
});
}
reset() {
this.clearHighlights();
this.render();
}
}