Javascript – Mapping and Type Checking

Type Checking

To check that an object has been created from the right class:

function typeCheck(configuration) {
     for (var i = 0; i < configuration.length; i++) {
          var element = configuration[i];

          if (element[0].constructor.name != element[1]) {
               console.log("ERROR: type check failed for type", element.type);
               return false;
          }
     }
     return true;
}

Usage:

if typeCheck([
     [ obj1, “Obj1Class” ],
     [ obj2, “Obj2Class” ],
     ...
]){
     //Here we are sure that the objects are of the required type
     ...
}

Mapping

To populate an object of a particular class from a JSon:

function getType(elem) {
     var type = elem == null
          ? "null"
          : elem instanceof Date
               ? "date"
               : elem instanceof Array
                    ? "array"
                    : typeof (elem);

     if (type == “object”) {
          type = "object<" + elem.constructor.name + ">";
     }
     return type;
}

function map(obj1, obj2) {
     if (!!target && !!object) {
          for (var key in obj1) {
               if (Object.prototype.hasOwnProperty.call(obj2, key)) {
                    var key1Type = getType(obj1[key]);
                    var key2Type = getType(obj2[key]);

                    if (key1Type == "null" || key2Type == "null") {
                         obj1[key] = obj2[key];
                    }
                    else if (key1Type == key2Type) {
                         if (key1Type.match(/^object<.+>$/)) {
                              obj1[key] = map(obj1[key], obj2[key])
                         } else {
                              obj1[key] = obj2[key];
                         }
                    }
                    else {
                         console.log("ERROR: mapping failed for property", key, "- wrong type");
                    }
               }
          }
          for (var key in obj2) {
               if (!Object.prototype.hasOwnProperty.call(obj1, key)) {
                    console.log("ERROR: mapping failed for property", key, "- unavailable");
               }
          }
     } else {
          console.log("ERROR: mapping failed - unavailable object(s)");
     }
     return obj1;
}

Usage:

var myObject = map(new MyObjectClass(), {
     prop1: “value1”,
     prop2: “value2”,
     ...
});
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s