How to know if a variable is a color?

(Another funny question) :upside_down_face:

if let c=color(15,20,56)

typeof c : object

and

c.constructor.name : nothing !!!

Help! How can I check that it is indeed a color ???


This code doesn’t work obviously with colors !

function className(object) {
  return object.constructor.name;
}

class V {
  static verif=true;

  static get(a, s, n) { // (anyType, type in a string, this) : any
    if (!V.verif) {
      return a;
    } else if ( typeof a === s) {
      return a;
    } else if (typeof a === 'object') {
      if (className(a)===s) return a;
      else {
        let type = typeof a;
        bugMessage("V Error, in : "+n+", asked : "+s+", but it was : "+type, true);
        return 0;
      }
    } else {
      let type = typeof a;
      bugMessage("V Error, in : "+n+", asked : "+s+", but it was : "+type, true);
      return 0;
    }
  }
}

P.S. In my project, I want to help the (future) user with explicit error messages.

In the many parameters of a theme for the GUI part, an error quickly arrived. As javascript is more lax for types than Java (Processing), which has advantages too, I try to add error messages in my program.

Hi @EricRogerGarcia,

Since p5.Color is a class/constructor, you can use instanceof to check if an object has that constructor in its prototype chain (meaning it’s an instance of p5.Color):

const c = color(255);
console.log(typeof c); // object
console.log(c.constructor.name); // Color
console.log(c instanceof p5.Color); // true
2 Likes

thanks : it works !! ! yesss !

"use strict";

// Workaround a P5 current problem with static field
p5.disableFriendlyErrors = true;

function className(object) {
  return object.constructor.name;
}

class V {
  static verif=true;

  static get(a, s, n) { // (anyType, type in a string, this) : any
    if (!V.verif) return a; // when debugging is finished : V.verif=false;
    else if (typeof a === s) return a; // for primitive types
    else if (typeof a === 'object') {
      if (className(a)===s) return a; // for classes (declared with "class" word)
      else if (s=="color") {
        if (a instanceof p5.Color) return a;
        else return V.error(a, s, n);
      } else if (s=="font") {
        if (a instanceof p5.Font) return a;
        else return V.error(a, s, n);
      } else return V.error(a, s, n);
    } //not an object !?
    return V.error(a, s, n);
  } // end get()

  static error(a, s, n) { //+ (anyType,String,object) : int
    let type = typeof a;
    bugMessage("V Error, in : "+n+", asked : "+s+", but it was : "+type, true);
    return 0;
  }
}

P.S. I don’t know why I forgot “instanceof” !!!

2 Likes