Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

determineVariableType #7

Open
thorst opened this issue Aug 7, 2023 · 0 comments
Open

determineVariableType #7

thorst opened this issue Aug 7, 2023 · 0 comments

Comments

@thorst
Copy link

thorst commented Aug 7, 2023

/**
 * 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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant