Hi all,
I'm having a little trouble with a bit of code I just wrote.
It's in an ASP.NET MVC application, so I can handle the following scenario back-end (C#) or front-end (JavaScript). It shouldn't really matter for the used method though.
Basically what I'm trying to do is the following:
I have the following list (third party component, can't change this):
Marker 1 start
Some object 1
Some object 2
Some object 3
Marker 1 end
Marker 2 start
Some object 4
Marker 3 start
Some object 5
Marker 3 end
Marker 2 end
Some object 6
And I want the following structure:
Marker 1
Some object 1
Some object 2
Some object 3
Marker 2
Some object 4
Marker 3
Some object 5
Anonymous marker
Some object 6
So as I see it I can do the following (pseudo code):
markers;
currentMarker;
foreach (obj in list)
switch (obj)
{
case 'Marker start':
newMarker = new {...};
if (currentMarker != null) {
currentMarker.markers.add(newMarker);
newMarker.parent = currentMarker;
} else {
markers.add(newMarker);
}
currentMarker = newMarker;
case 'Marker end':
if (currentMarker.parent) {
currentMarker = currentMarker.parent;
} else {
currentMarker = null;
}
default:
if (currentMarker == null) {
currentMarker = new anonymous Marker {...};
markers.add(currentMarker);
}
currentMarker.objects.add(obj);
}
return markers;
That's a lot of cases and if's and else's...
My method is already over 40 lines of code and I'm pretty sure I'll add some lines and if's as time passes (what if a Marker start has no end marker? etc.).
Is there a better, more readable, more maintainable way to handle the scenario? Maybe some pattern or algorithm that can save the day?
I can't be the first one to have this problem :)
Thanks!