Tag: javascript

  • Universal getter for plain JS objects.

    Many times in JavaScript we have to reach deep into objects to access fields that could possibly not be there at all; for example let’s assume I have a JS object called options into which I’ve just read an entire JSON configuration file. Trying to access a field like options.application.cache.enable directly will potentially fail (e.g. when any of the intermediate levels is missing)…

    if (options.application.cache.enable) {
        // do stuff
    }
    

    …therefore this kind of work will usually involve some kind of testing for the existence of each level, so as to gracefully handle any misbehaving data. Also, many times I’ve seen the following approach used in these scenarios which is quite bad for anything more than a single depth level:

    if (options && options.application && ...) {
        // do stuff
    }
    

    So, just as a little helper, here is a small method that may prove to be quite handy when having to deal with data whose structure we’re not certain of (here’s a proper Gist entry).
    (more…)

  • A simple(r) approach for class-based OOP in JavaScript.

    Like others before me, I found JavaScript’s prototype-based OOP support – while very powerful – quite cumbersome in some situations where I needed a certain structure or hierarchy of objects, situations in which one quickly comes to the conclusion that the best answer would be the concept of a Class.

    However, while I am well aware that the web is filled with various implementations of classical (i.e. class-based) object orientation in JavaScript, I can not help the feeling that they are over-engineered and over-complicated without need, quite often attempting to provide more functionality than is actually necessary. In short, I don’t feel they’re “classical” at all.

    This is why I started working on my own implementation of classical OOP  in JavaScript, which is shown below. Currently this is only a proposal, although I already started using it in one of my projects. Anyway, let’s look at it first then I’ll try and explain how it works.

    The Code

    /** Class factory. */
    function Class(members) {
    
        // proxy constructor
        var Proxy = function() {
            for (var item in members) {
                this[item] = members[item];
            }
        };
    
        // proxy inheritance
        Proxy.prototype = (members.base || Class).prototype;
    
        // class constructor
        var Build = members.init || function() {};
    
        // class inheritance
        Build.prototype = new Proxy();
        Build.prototype.base = Proxy.prototype;
        Build.prototype.constructor = Build;
    
        // ready
        return Build;
    }

    That is all, and this little function can have a whole world of nifty consequences like deep inheritance or access to the super-class via this.base (and others). But here is what happens: the basic principle at work here is the Proxy object, which essentially, contains all the members of our new class (the ones that are passed to the Class factory function as the members parameter). (more…)

  • Command-line option parser in JavaScript.

    Here’s a small but very effective command-line option parser written in JavaScript (uses NodeJs). You can get the up-to-date source code at http://gist.github.com/982499.

    I wrote this because I needed it for a project and I did not think it was worth it to install some npm package just for this. The comment should explain most things you will need but ask me if you don’t understand something. Note that this code is not well tested (yet!) since I just wrote it this morning so post a comment when you find a bug.

    Supports:

    • Short and long options (i.e. ‘-t|--test‘).
    • Option parameters (i.e. ‘-f /etc/resolv.conf‘).
    • Mandatory options.
    • Implicit help option.
    • Option callback functions.
    • Cumulated short options (i.e. ‘-ab‘).
    • Repeatable options (i.e. ‘--add value1 --add value2‘).
    • Non-option arguments.

    Notes (extracted from the comments):

    • Parser is case-sensitive.
    • The ‘-h|–help’ option is provided implicitly.
    • Successfully parsed options will be available as fields in the “options” object.
    • Non-option arguments found will be available in order in the “arguments” array.
    • Options and their parameters must be separated by space.
    • Either one of «short» or «long» must always be provided.
    • The «callback» function is optional and is invoked each time the option is encountered.
    • Cumulated short options are supported (i.e. ‘-tv‘).
    • If an error occurs, the process is halted and the help message is shown.
    • Options with the “multiple” attribute will be cumulated into arrays (even if found only once).
    • The parser does *not* test for duplicate definitions in the schema array.

    See the code for everything else you need to use it (i.e. a sample schema definition). I will not waste any more time talking about it; if you like it, paste it at the top of your NodeJS script and start playing with it, e.g.:

    $ node options.js -tf /some/file.txt foo bar

    Also, please tell me about any improvements or fixes you produce. Thanks and… enjoy! 🙂