Search code examples
javascripttypescripttypescript-class

Pre-condition checking in typescript


I have a typescript class where there are methods for checking the variables type. How do I determine at the beginning of the doProcess() which method to use for processing the following?

class MyClass {

public static arr : any[] = [];

// main method
public static doProcess(object : object , justForObjects : boolean = false){
    if (justForObjects){
        // here should specify which checking method use in *** line
    } else {

    }

    for (let key in object){
        if (object.hasOwnProperty(key)){
            if (/* *** */){
                MyClass.doProcess(object[key] , justObjects)
            } else {
                MyClass.arr.push(object[key])
            }
        }
    }

return MyClass.arr;

}

 // check variables type methods
 private static is_object(value : any){
     return !!(typeof value === 'object' && !(value instanceof Array) && value);
 }
 private static is_object_or_array(value : any){
     return !!(typeof value === 'object' && value);
 }

}

let object = {
 'main color' : 'black',
 'other colors' : {
     'front color' : 'purple',
     'back color' : 'yellow',
     'inside colors' : {
         'top color' : 'red',
         'bottom color' : 'green'
     }
 }
}

MyClass.doProcess(object , true);

I know it can be done in the same for loop (as below), but I would like to find a way to do it first.

    for (let key in object){
        if(object.hasOwnProperty(key)){
            if (justForObjects){
                if (MyClass.is_object(object[key])){
                    // do something
                }
            } else {
                if (MyClass.is_object_or_array(object[key])){
                    // do something else
                }
            }
        }

    }

Thanks for your tips


Solution

  • Functions can be simply assigned to variables, i.e.:

    public static doProcess(obj : object , justForObjects : boolean = false) {
    
        var check_fn = justForObjects ? MyClass.is_object : MyClass.is_object_or_array;
    
        for (let key in obj) {
            if (check_fn(obj[key])) ...
        }
    
    }
    
     // check variables type methods
     private static is_object(value : any) : boolean { ... }
     private static is_object_or_array(value : any) : boolean { ... }