In my current project I have objects of the following structure:
CanvasBundle - Object
- Some elements...
gridCanvas
axesCanvas
functions[]
(contains unknown number offunctionCanvases
)overlayCanvas
I'd like to write an iterator which would iterative over all the canvases (grid
/axes
/func
/func1
/func2
/.../overlay
).
I've currently implemented it like this:
function makeCanvasBundleIterator(canvasBundle) {
var nextIndex = 0;
var functionIndex = 0;
return {
next: function() {
var value;
switch (nextIndex) {
case 0:
value = canvasBundle.grid;
break;
case 1:
value = canvasBundle.axes;
break;
case 2:
value = canvasBundle.functions[functionIndex];
break;
case 3:
value = canvasBundle.overlay;
break;
default:
break;
}
if (nextIndex != 2 || functionIndex == canvasBundle.functions.length -1) {
nextIndex++;
} else {
functionIndex++
}
return nextIndex <= 4 ?
{value: value, done: false} :
{done: true};
}
};
}
This allows me to do the following:
var it = makeCanvasBundleIterator(canvasBundle);
var next;
while (!(next = it.next()).done) {
console.log(next.value);
}
Coming from C, this code does not look clean at all. Since I'm a real JS beginner, I'd like a review with suggestions/advice how I can clean it up. Maybe there even is a completely different/better approach.
gridCanvas
,axesCanvas
, etc.) corresponds to an HTML-canvas element. These HTML-canvases all lay on top of each other (overlapping) and together they create a full picture. All these canvases are necessary to draw multiple layers, etc. The complete picture is stored in one of theCanvasBundles
shown above. When I need to redraw a whole picture, I need to iterate over all the contained canvases (to redraw every single one of them). The code above does the job, but I just think the code looks kind of dirty. – LastSecondsToLive yesterday