Skip to content

Commit 6f8dff5

Browse files
cleanup sorting logic
1 parent d163c4c commit 6f8dff5

File tree

1 file changed

+57
-1
lines changed

1 file changed

+57
-1
lines changed

lib/features/sorting/base/view_model/sorting_notifier.dart

Lines changed: 57 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import 'package:algorithm_visualizer/core/helpers/screen_size.dart';
22
import 'package:algorithm_visualizer/core/resources/theme_manager.dart';
3+
import 'package:collection/collection.dart';
34
import 'package:flutter/material.dart';
45
import 'package:flutter_riverpod/flutter_riverpod.dart';
56
import 'package:flutter_screenutil/flutter_screenutil.dart';
@@ -125,5 +126,60 @@ abstract class SortingNotifier extends StateNotifier<SortingNotifierState> {
125126
}
126127
}
127128

128-
Future<void> buildSort();
129+
Future<void> buildSort() async {
130+
final list = List<SortableItem>.from(state.list);
131+
final values = list.map((e) => e.value).toList();
132+
133+
final steps = buildSorting(values);
134+
135+
for (final step in steps) {
136+
if (operation != SortingEnum.played) return;
137+
138+
switch (step.action) {
139+
case SortingStatus.compared:
140+
list[step.index1] = list[step.index1].copyWith(sortedStatus: SortingStatus.compared);
141+
list[step.index2] = list[step.index2].copyWith(sortedStatus: SortingStatus.compared);
142+
state = state.copyWith(list: list);
143+
144+
await Future.delayed(speedDuration);
145+
146+
break;
147+
148+
case SortingStatus.swapped:
149+
list[step.index1] = list[step.index1].copyWith(sortedStatus: SortingStatus.swapped);
150+
list[step.index2] = list[step.index2].copyWith(sortedStatus: SortingStatus.swapped);
151+
state = state.copyWith(list: list);
152+
153+
await Future.delayed(speedDuration);
154+
155+
list.swap(step.index1, step.index2);
156+
157+
final positions = Map<int, Offset>.from(state.positions);
158+
final tempPosition = positions[list[step.index1].id]!;
159+
positions[list[step.index1].id] = positions[list[step.index2].id]!;
160+
positions[list[step.index2].id] = tempPosition;
161+
162+
state = state.copyWith(list: list, positions: positions);
163+
break;
164+
165+
case SortingStatus.unSorted:
166+
list[step.index1] = list[step.index1].copyWith(sortedStatus: SortingStatus.unSorted);
167+
list[step.index2] = list[step.index2].copyWith(sortedStatus: SortingStatus.unSorted);
168+
state = state.copyWith(list: list);
169+
break;
170+
171+
// i don't want to make it green while sorting and mark all of them at once as green at the end
172+
case SortingStatus.sorted:
173+
case SortingStatus.none:
174+
list[step.index1] = list[step.index1].copyWith(sortedStatus: SortingStatus.none);
175+
state = state.copyWith(list: list);
176+
break;
177+
}
178+
179+
await Future.delayed(speedDuration);
180+
}
181+
182+
await greenSortedItemsAsDone();
183+
}
184+
List<SortingStep> buildSorting(List<int> values);
129185
}

0 commit comments

Comments
 (0)