Code rewrite

I think it's important to iterate over code - just like you do with a design. The primary goal is to get something to work in shortest possible time. After it works, try to figure out how to improve it. I will take a concrete example I did today in JavaScript.

I figured out that it would be smart to have CTRL+B for bold in Todoist. My initial approach looked like this:

//ctrl+u
if(e.ctrl && e.key == 117) {
    insert_at_cursor('u');
    return false;
}
//ctrl+b
if(e.ctrl && e.key == 98) {
    insert_at_cursor('b');
    return false;
}
//ctrl+i
if(e.ctrl && e.key == 105) {
    insert_at_cursor('i');
    return false;
}
//ctrl+i
if(e.ctrl && e.key == 104) {
    insert_at_cursor('i');
    return false;
}

That's readable and decent code, but one could rewrite it into a switch statement:

if(e.ctrl) {
    var cancel_event = false;
    switch(e.key) {
        case 117:
            insert_at_cursor('u');
            cancel_event = true;
        case 98:
            insert_at_cursor('b');
            cancel_event = true;
        case 105:
            insert_at_cursor('i');
            cancel_event = true;
        case 104:
            insert_at_cursor('hl');
            cancel_event = true;
    }

    if(cancel_event)
        return false;
}

A little better, and after some thinking, here is my final 4 line solution:

var key_to_tag = {117: 'u', 98: 'b', 105: 'i', 104: 'hl'};
if(e.ctrl && AJS.isIn(e.key, [117, 98, 105, 104])) {
    insert_at_cursor(key_to_tag[e.key])
    return false;
}

Smart and beautiful.

Code · JavaScript · Tips 10. Mar 2007
© Amir Salihefendic. Powered by Skeletonz.