2010-12-10 14 views
1

ここでこれを聞いても大丈夫かどうかはわかりません。もしそうでなければ、ただ投票してください。しかし私はアスペクト比関数の効率についての意見を探しています。以下は、アスペクトを決定し、画像のサイズを制限する関数です。どうだった?JavaScriptコードの効率

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

"auto"ではなく "either"とコメントする必要があります。 –

+1

いいですね - 実際にアルゴリズムの速度に問題がありますか? – Piskvor

+0

私は問題を抱えていません。 – dubbelj

答えて

2

あなたは、パフォーマンスをチェックするためにhttp://code.google.com/closure/compiler/を使用することができ、単一の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

にそれを凝縮できました。

およびhttp://jslint.com/は、メモリリークやその他のエラーを検索します。