2010-12-10 9 views
1

여기에이 질문을해도 괜찮은지 확실하지 않습니다. 그렇지 않다면, 저를 투표하십시오. 하지만 내 종횡비 기능의 효율성에 대한 의견을 찾고 있어요. 다음은 화면의 크기를 결정하고 이미지의 크기를 제한하는 기능입니다. 내가 어떻게 했지?자바 스크립트 코드 효율성

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