1

I'm not really sure if it's okay to ask this here. If not, just vote me down. But i'm looking for an opinion on the efficiency of my aspect ratio function. The following is a function to determine the aspect, and limit the size of an image. How did i do?

function constrainTwoNumbers(options){

d = {
    dir: 'either', // direction: 'auto', 'vertical' or 'horizontal'. What side of the image do you want to constrain?
    orgw:0,
    orgh:0,
    target:100,
}

// merge the options with the default values
o = $.extend(d, options);

// create object to write results into
var result = [];

switch(o.dir){
    case 'either':      
        // no direction is set, limit the largest side.
        // determine what the orientation is.
        if(o.orgw > o.orgh){ //landscape
            aspect = o.orgw / o.target;
        }else if(o.orgw < o.orgh){ //portrait
            aspect = o.orgh / o.target;
        }else if(o.orgw === o.orgh){ // the image is square. Just pass both dimensions as targeted
            result.w = o.target;
            result.h = o.target;
            return result;
        }                   
        break;
    case 'horizontal':      
            aspect = o.orgw / o.target;
        break;
    case 'vertical':            
            aspect = o.orgh / o.target;
        break;
}

result.w = Math.round(o.orgw / aspect);
result.h = Math.round(o.orgh / aspect);     
return result;
}
3
  • 1
    need to change your comment to say "either" instead of "auto". Commented Dec 10, 2010 at 9:50
  • 1
    Looks okay - are you actually having problems with the algorithm's speed? Commented Dec 10, 2010 at 9:54
  • I'm not having problems, just eager to improve. Commented Dec 10, 2010 at 10:22

2 Answers 2

2

You could condense it to a single if/else

function constrainTwoNumbers(options){

    var d = {
        dir: 'either', // direction: 'either', 'vertical' or 'horizontal'. What side of the image do you want to constrain?
        orgw:0,
        orgh:0,
        target:100
    };

    // merge the options with the default values
    var o = $.extend(d, options);

    // create object to write results into
    var result = [];
    if ((o.dir === 'either' && o.orgw > o.orgh) || (o.dir === 'horizontal'))
    {
      aspect = o.orgw / o.target;
    }
    else
    {
      aspect = o.orgh / o.target;
    }

    result.w = Math.round(o.orgw / aspect);
    result.h = Math.round(o.orgh / aspect);     
    return result;
}
Sign up to request clarification or add additional context in comments.

Comments

1

You can use the http://code.google.com/closure/compiler/ to check for performance.

And http://jslint.com/ to look for memory leaks and other errors.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.