connect-examples icon indicating copy to clipboard operation
connect-examples copied to clipboard

determineVariableType

Open thorst opened this issue 2 years ago • 0 comments

/**
 * Determines the type of a given variable. 
 * If the variable is a Java instance, it returns the Java class name.
 * If the variable is a JS object, it returns the JS constructor name (if available) 
 * or extracts the type from the default toString representation (as a fallback).
 * Otherwise, it returns the JS primitive type.
 * 
 * @param {any} variable The variable whose type needs to be determined.
 * @return {string} The type of the variable.
 */
function determineVariableType(variable) {
    // Check for Java instances
    if (variable instanceof java.lang.Object) {
        return variable.class.name;
    }
    
    // Check for JS objects (excluding null)
    if (typeof variable === 'object') {
        // If constructor.name is available, use it. Otherwise, use the toString fallback and extract the type
        if (variable && variable.constructor && variable.constructor.name) {
            return variable.constructor.name;
        } else {
            let toStringType = Object.prototype.toString.call(variable);
            return toStringType.slice(8, -1);  // Extracts "Type" from "[object Type]"
        }
    }
    
    // Return JS primitive type
    return typeof variable;
}

thorst avatar Aug 07 '23 16:08 thorst