skip to Main Content

I try to create a simple script that will take RGB-16 colors and convert them to RGB-8. The script works, but for some reason I cannot figure out how to convert it to function so that it will work for two different palettes. Using palette.forEach causes an error. The problem seems to be easy to understand, but I cannot spot it out.

const system41 = [
  [65535, 65535, 65535],
  [64512, 62333,  1327],
  [65535, 25738,   652]
];

const system7 = [
  [65535, 65535, 52428],
  [65535, 52428, 39321],
  [52428, 39321, 26214]
];

function convert(palette) {
    palette.forEach((child) => {
        const rgb8 = child.map(value => Math.round(value / 257));
        document.querySelector('#' + palette).innerHTML += rgb8.join(', ') + 'n';
    });
}

convert('system41');
convert('system7');
<p>System 4.1 system colors</p>
<pre id="system41"></pre>

<p>System 7 icon colors</p>
<pre id="system7"></pre>

2

Answers


  1. The first thing is that you should log the palette right after you define it in the function convert() you will see the reason why you can not achieve it.

    Login or Signup to reply.
  2. Store your arrays in an object so you can perform string-wise lookups.

    const palettes = {
      system41: [
        [65535, 65535, 65535],
        [64512, 62333, 1327],
        [65535, 25738, 652]
      ],
      system7: [
        [65535, 65535, 52428],
        [65535, 52428, 39321],
        [52428, 39321, 26214]
      ]
    };
    
    function convert(palette) {
      palettes[palette].forEach((child) => {
        const rgb8 = child.map(value => Math.round(value / 257));
        document.querySelector('#' + palette).innerHTML += rgb8.join(', ') + 'n';
      });
    }
    
    convert('system41');
    convert('system7');
    <p>System 4.1 system colors</p>
    <pre id="system41"></pre>
    
    <p>System 7 icon colors</p>
    <pre id="system7"></pre>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search