Home > Software design >  Function to generate specified number of random hex and rgb colors
Function to generate specified number of random hex and rgb colors

Time:06-21

Trying to write a function that generates a specified amount of random rgb or hex colors. It takes 'rgb' or 'hex'(type) and then 'n'(quantity to generate) as parameters, but I'm getting NaN when running code. Here's what I have written:

function generateColors(type, n) {
    let result = ''
    var quantity = Number(n)
    if (type === 'rgb') {
        let num = Math.round(0xffffff * 
Math.random());
        let r = num >> 16
        let g = num >> 8 & 255
        let b = num & 255
    return ('rgb('   r   ', '   g   ', '   b   ')') * quantity;
  } else if (type === 'hexa') {
        let hexDigits = '0123456789ABCDEF'
        let randomHex= []
        for (var i = 0; i < 6; i  ) {
            randomHex  = 
hexDigits.charAt(Math.floor(Math.random() * 
hexDigits.length));
    }
    return [randomHex] * quantity; 
  } else {
      console.log('type not applicable')
  }
  return result
}  
console.log(generateColors('rgb', 3))
console.log(generateColors('hexa', 3))

Not sure what I'm missing, or if I should do a switch statement instead, but any advice is welcome.

CodePudding user response:

you will need to use loop...

you can loop n times inside the function. push the output into the result and return the result. it will look like something like this:

function generateColors(type, n) {
  let result = [];
  for (let x = 0; x < n; x  ) {
    if (type === "rgb") {
      let num = Math.round(0xffffff * Math.random());
      let r = num >> 16;
      let g = (num >> 8) & 255;
      let b = num & 255;
      result.push("rgb("   r   ", "   g   ", "   b   ")");
    } else if (type === "hexa") {
      let hexDigits = "0123456789ABCDEF";
      let randomHex = "";
      for (var i = 0; i < 6; i  ) {
        randomHex  = hexDigits.charAt(
          Math.floor(Math.random() * hexDigits.length)
        );
      }
      result.push(randomHex);
    } else {
      console.log("type not applicable");
    }
  }
  return result;
}
console.log("rgb", generateColors("rgb", 3));
console.log("hex", generateColors("hexa", 3));

Working example - dont forget to open the console ;)

CodePudding user response:

Or, slightly shorter:

function mulcol(n,hex){
 function rndcol(hex){
  let col=[1,2,3].map(v=>Math.floor(Math.random()*256).toString(hex?16:10).padStart(hex?2:1,"0"));
  return hex?`#${col.join("")}`:`rgb(${col.join(",")})`;
 }
 return [...Array(n)].map(v=>rndcol(hex));
}
 
console.log(mulcol(3)); // RGB output
console.log(mulcol(5,1));// hex output

  • Related