Functions

Returning data + Commenting

Below are several functions that will return random colors.

Every function is preceeded by a comment of it’s purpose. A basic comment like the one for the getRandomGray() function should be provided. There are more professional documentation styles like JSDoc. Here is a blog post about it. But this is not mandatory for our purpose of artistic/experimental programming, it’s more important for professional software development. Nevertheless it may be good for the workflow even for our purpose. Having a detailed documentation of the function is helpful later on, because you don’t have to look into a function, you just read from the documentation what it does, what the input should look like and what you’ll get in return. The functions below have comments with different amount of detail.

// Get a random grayscale color.
function getRandomGray() {
  return color(random(256));
}

/**
 * Get a random RGB color.
 */
function getRandomRGB() {
    return color(random(256), random(256), random(256));
}

/**
 * Get a random RGBA color.
 * @return {color} - A random RGBA color.
 */
function getRandomRGBA() {
    let r, g, b, a;
    r = random(256);
    g = random(256);
    b = random(256);
    a = random(256);
    return color(r, g, b, a);
}

/**
 * Get a random color based on number of channels.
 * @param {number} channels - The number of color channels (1, 3, 4).
 * @return {color} - A random color with given channels.
 */
function getRandomColor(channels) {
  if (channels == 3) {
    let r, g, b;
    r = random(256);
    g = random(256);
    b = random(256);
    return color(r, g, b);
  } else if (channels == 4) {
    let r, g, b, a;
    r = random(256);
    g = random(256);
    b = random(256);
    a = random(256);
    return color(r, g, b, a);
  } else {
    return color(random(256));
  }
}

/**
 * Get a random color of a given range, based on number of channels.
 * @param {number} channels - The number of color channels (1, 3, 4).
 * @param {number} [min=0] - Minimum random value (optional).
 * @param {number} [max=256] - Maximum random value (optional).
 * @return {color} - A random color with given channels.
 */
function getRandomColorRange(channels, min=0, max=256) {
  if (channels == 3) {
    let r, g, b;
    r = random(min, max);
    g = random(min, max);
    b = random(min, max);
    return color(r, g, b);
  }
  else if (channels == 4) {
    let r, g, b, a;
    r = random(min, max);
    g = random(min, max);
    b = random(min, max);
    a = random(min, max);
    return color(r, g, b, a);
  } 
  else {
    return color(random(min, max));
  }
}