-1

So, i wrote this Javascript Function Which Return a Hex code as a String. Is there a way through which i can reduce the size of this code

function RandomHexGenerator(Opacity) {
    const Chars = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'a', 'b', 'c', 'd', 'e', 'f'];
    let HexContainer = [];
    while (HexContainer.length != 6) {
        HexContainer.push(Chars[Math.floor(Math.random() * Chars.length)]);
    }
    let HexString = HexContainer.toString();
    let CleanString = HexString.replaceAll(',', '');
    if (Opacity != true) {
        return '#' + CleanString;
    } else {
        let lastDigits = [];
        while (lastDigits.length != 2) {
            lastDigits.push(Chars[Math.floor(Math.random() * Chars.length)]);
        }
        let StringLastDigit = lastDigits.toString();
        let CleanLastDigit = StringLastDigit.replaceAll(',', '');

        return '#' + CleanString + CleanLastDigit;
    }
}

I Just want to Know/Learn If there is way through which i can reduce the size of this code

  • Create an 8 digit hex string from the beginning - then, `if(!Opacity)` remove the last two chars. Then just return the string. – Randy Casburn Dec 22 '22 at 13:47
  • 1
    [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask): _"Write a title that summarizes the **specific problem**"_ - _"How to optimize..."_ is not a problem nor a specific task. You might get an answer at [Code Review](https://codereview.stackexchange.com) – Andreas Dec 22 '22 at 13:47
  • Use `Opacity` to determine how long a string you want, then use a single loop to build that string. – Scott Hunter Dec 22 '22 at 13:50
  • small?? how about single line?? return "#"+(opacity?new Number(Math.floor(Math.random()*(256*256*256*256))):new Number(Math.floor(Math.random()*(256*256*256)))).toString(16); – Anubhav Sharma Dec 22 '22 at 13:59
  • @AnubhavSharma `new Number`? Really? You also forgot zero-padding. Even this code can be shortened: `"#" + Math.floor(Math.random() * (2 ** (24 + Boolean(opacity) * 8))).toString(16).padStart(6 + Boolean(opacity) * 2, "0")`, etc. – Sebastian Simon Dec 22 '22 at 14:16

2 Answers2

2
function randomHexColor(includeOpacity) {
  const chars = '0123456789abcdef';
  let color = '#';
  for (let i = 0; i < 6; i++) {
    color += chars[Math.floor(Math.random() * chars.length)];
  }
  if (includeOpacity) {
    for (let i = 0; i < 2; i++) {
      color += chars[Math.floor(Math.random() * chars.length)];
    }
  }
  return color;
}

//OR

function randomHexColor(includeOpacity) {
  let color = '#';
  for (let i = 0; i < 6 + (includeOpacity ? 2 : 0); i++) {
    color += Math.floor(Math.random() * 16).toString(16);
  }
  return color;
}

//OR

const rndHexColor = o => '#' + [...Array(6 + (o ? 2 : 0))].map(() => Math.floor(Math.random() * 16).toString(16)).join('');

But remember that smaller code does not mean better code (except for a code golf challenge), on the contrary, the more explicit and clear the code is, the better it would be.

Elie Asmar
  • 2,995
  • 4
  • 17
  • 30
0

Maybe having a shorter function to generate an hex number (toString) given a number of digits and a macro function that will call the former one based on the Opacity condition:

console.log( RandomHexGenerator(true) );
console.log( RandomHexGenerator(false) );

function getRandomHex(digits){
  const max = (16 ** digits) -1;
  return Math.floor(Math.random()*max).toString(16);
}

function RandomHexGenerator(Opacity) {            
    return (Opacity !== true) ? `#${getRandomHex(6)}` : `#${getRandomHex(8)}`;        
}
Diego D
  • 6,156
  • 2
  • 17
  • 30