Skip to content Skip to sidebar Skip to footer

Is It Possible To Convert Many If/else Statements To A Dictionary For Space Efficiency?

In Javascript is it possible to convert many if/else statements to a dictionary for space efficiency? For example I have the following which is longer in reality if (namelen < 2

Solution 1:

You could try something like this:

var dict = [
    { max: 0 },
    { max: 20,  str: 'hurray!' },
    { max: 90,  str: 'too long' },
    { max: 120, str: 'go away you cheater' }
];
for(var i = 1; i < dict.length; i++){
    if(namelen > dict[i-1].max && lastname < dict[i].max){
        form.innerHTML = dict[i].str;
    }
}

So, if namelen is greater than the "previous max", and lastname is less than max, set the innerHTML.

Notice that I initialized my i as 1, so the for loop will start looking at dict[1]. This way, I can use that first object in to make namelen > dict[i-1] work.

Post a Comment for "Is It Possible To Convert Many If/else Statements To A Dictionary For Space Efficiency?"