2

I'm creating map markers, and I want to assign a different colour to each county on the map.

I don't know in advance how many counties there will be showing on the map, so I need to figure out a way to assign an unlimited number of colours.

At the moment, I'm assigning a colour to each county using the following code, but I run into a problem when I pop() the list too many times:

var colours = ['6183A6', '3A66A7', '3B4990', '5B59BA'];
var h_colours = []; // associative array 
function addMarker(county, colour) {
if (colour==undefined) {
    if (h_colours[hundred]==undefined) {
            h_colours[hundred] = colours.pop();
    } } }

Is there a way I could cycle through the list without actually deleting items, and continuing from the start of the list when I reach the end?

thanks!

2 Answers 2

9

Yes.

 var getNextColour = (function() {
   var colours = ['6183A6', '3A66A7', '3B4990', '5B59BA'];
   var cc = 0;
   return function() {
     var rv = colours[cc];
     cc = (cc + 1) % colours.length;
     return rv;
   };
 })();

Now you can just say:

 if (colour == undefined) colour = getNextColour();

or simply

 colour = colour || getNextColour();

Of course, applying the colors to the elements of the map such that you don't color adjacent areas with the same color is a considerably more interesting problem.

Sign up to request clarification or add additional context in comments.

Comments

1

You can use a counter for the index in the array.

Increment whenever you fetch a color, reset it to 0 when it is the size of the array -1.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.