Type checked functions

by egon

HTML

<div id="center">
    <hr />
    <div id="logDiv"></div>
    <script type="text/javascript">       
        log = (function(){
            var logDiv = document.getElementById("logDiv");
            return function(){
                var args = [];
                for(var i=0; i < arguments.length; i++)
                    args.push( arguments[i] );
                logDiv.innerHTML = "<p>" + JSON.stringify(args) + "</p>" + logDiv.innerHTML;
            };
        })();
        
    </script>
</div>

CSS

body {
    margin : 0 0;
    width  : 100%;
    background: #000;
}
#center {
    align : center;
    margin : 0 auto;
    margin-top : 30px;
    width : 400px;
}

hr {
    color: #fff;
}

#logDiv {
    font:normal 12px/16px Courier New, monospace;
    color: #fff;
    height: 400px;
    overflow: scroll;
}

JavaScript

Object.prototype.method = function( name, typedef, func ){
    log("test");
    var args = [],
        types = [],
        f;
    for( var n in typedef ){
        if( ! typedef.hasOwnProperty(n) ) 
            continue;
        args.push( n );
        types.push( typedef[n] );
    }

    this.prototype[name] = function(){
        if( arguments.length != types.length ){
            log("Invalid number of arguments!", arguments.length, types.length);
        }
        for(var i = 0; i < types.length; i++){
            if( ! (arguments[i].constructor === types[i]) ){
                log("Wrong type!", arguments[i], types[i].toString());
                return;
            }
        }
        func.apply(this, arguments);
    };
};

function Thing(){
}

Thing.method( "testing",
              { arr: Array, st: String }, 
              function(arr, st){
                  log( st, arr );
              });

/* Thing.method( "testing",
              [Array, String], 
              function(arr, st){
                  log( st, arr );
              });
*/

var thing = new Thing();

var a = [1,2,3,4],
    b = "hello!",
    c = "who's there!";


thing.testing(a,b);
thing.testing(a,c);
thing.testing(b,c);