Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get every valid hex code in javascript

Tags:

This a little thing that i started at work two days ago thinking it would be a quick little brain problem then ill get back to eating my lunch. However im struggling. I want to get an array of all valid hexadecimal color codes. Without crashing the browser preferably.

This is what i came up with so far.

app.directive 'randomColor', () ->
  link: (scope) ->
    scope.colors = new Array
    col = 0x0
    while col <= 0xFFF
      if (col > 0x111 && col < 0xFFF)
        scope.colors.push '#' + col
      col++
    autocolor = (hexcode) ->
      colorChange = () ->
        $("#colorvomit").append("<span style='padding: 1px 10px 1px 10px;background-color: " +hexcode+";border: 1px solid black;'></span>")
      setTimeout(colorChange, 5000)
    _.each(scope.colors, autocolor)

Bare in mind im using coffescript and angular js. With the underscore library so i can use _.each.

So i get this as the result

enter image description here

you can see there are a lot of white squares at the bottom and it goes on forever a long time because it comes back with invalid hex codes like #1223 (4 digit ones).

So here is my question what is the best way to get all valid hexadecimal color codes lets say 6 long i have 3 long (FFF) because it crashes otherwise without getting invalid codes. Appreciate all your help and i think this would be a fun question to ask.

I have done my research and cant find anything similar. Because we want them all preferably in order as well like 111 112 113 ect...

like image 812
Morphasis Avatar asked Mar 27 '16 23:03

Morphasis


1 Answers

Rather than using a nested loop, I just converted decimal from/to hex. Not better, just different. Fiddle below, showing operation.

*Edit: This code is modified to run all 16 million colors. The fiddle still uses 8 bit per color (#000; brief notation), so that it won't take forever to run

var $cv= $("#colorvomit");
for(var col=parseInt("000000", 16); col<=parseInt("ffffff", 16); col++) {
    var hex = col.toString(16);
  hex = '0'.repeat(6-hex.length) + hex;
    $cv.append('<span style="background-color:#'+hex+';"> &nbsp; </span>');
}

https://jsfiddle.net/4tm54u62/1/

like image 197
David784 Avatar answered Oct 11 '22 13:10

David784