Javascript代码效率

时间:2010-12-10 09:41:50

标签: javascript jquery

我不确定在这里问这个问题是否可以。如果没有,请投反对票。但我正在寻找关于我的宽高比功能效率的意见。以下是确定方面和限制图像大小的功能。我是怎么做到的?

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;
}

2 个答案:

答案 0 :(得分:2)

您可以将其压缩为单个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;
}

答案 1 :(得分:1)

您可以使用http://code.google.com/closure/compiler/检查效果。

http://jslint.com/查找内存泄漏和其他错误。