Rewriting code

The great thing about using your own stuff is that you can remove or rewrite code!

AJS.partial (JavaScript curry function) looked like this:

function partial(fn) {
    var args = AJS.forceArray(arguments);
    args = args.slice(1, args.length).reverse();
    return AJS.bind(fn, null, args, false, true);
}

Using bind was "smart", but unfortunately the above code had a bug when one did this:

function add(a, b, c) {
   return a+b-c;
}

add_5 = AJS.partial(add, 5);
add_5(3, 4); //Returns 6, should be 4

I could debug it, but I chose to rewrite the damn code and make it more readable:

function partial(fn) {
    var args = AJS.$FA(arguments);
    args.shift();
    return function() {
        args = args.concat(AJS.$FA(arguments));
        return fn.apply(window, args);
    }
}

I also rewrote AJS.bind (or deleted a lot of code). At one time I thought following function signature was "smart":

bind: function(fn, scope, /*optional*/ extra_args, dont_send_event, rev_extra_args)

The new signature looks like this:

bind: function(fn, scope, /*optional*/ extra_args)

Implementation went from 20 lines to around 5 :)

Code · Code improvement · Code rewrite · JavaScript · Tips 17. Apr 2007
3 comments so far

Amir,
where can I find the code for the new AJS.bind()?

thanks
T

Any progress on that GMail thing? =D

Tim:

bind: function(fn, scope, /*optional*/ extra_args) {
    extra_args = AJS.$A(extra_args);
    var scope = scope || window;
    return function() {
        var args = AJS.$FA(arguments).concat(extra_args);
        return fn.apply(scope, args);
    };
}

Siemen:
I have developed it, but I need to document it, so users easily can install it. I plan to launch it next Monday.

Post a comment
Commenting on this post has expired.
© 2000-2009 amix. Powered by Skeletonz.