개요

함수 로직이 거의 같고, 리터럴 값만 다르다면, 다른 부분만 매개변수로 받아 중복을 제거한다.

 

간단한 예시



//가장 간단한 예시
function tenPercentRaise(aPerson){
    aPerson.salary = aPerson.salary.multiply(1.1);
}
function fivePercentRaise(aPerson){
    aPerson.salary = aPerson.salary.multiply(1.05);
}
//함수 매개변수화
function rise(aPerson, factor){
    aPerson.salary = aPerson.salary.multiply(1+factor);
}

 

간단하지 않은 예제



function baseCharge(usage){
    if(usage < 0) return usd(0);
    const amount = bottomBand(usage) * 0.03
        + middleBand(usage) * 0.05
        + topBand(usage) * 0.07;
    return usd(amount);
}
function bottomBand(usage){
    return Math.min(usage, 100);
}
function middleBand(usage){
    return usage > 100 ? Math.min(usage,200) - 100 : 0;
}
function topBand(usage){
    return usage > 200 ? usage - 200 : 0;
}


function baseCharge(usage){
    if(usage < 0) return usd(0);
    const amount = bottomBand(usage) * 0.03
        + withinBand(usage, 100, 200) * 0.05
        + topBand(usage) * 0.07;
    return usd(amount);
}
function bottomBand(usage){
    return Math.min(usage, 100);
}
//통합할 함수를 선정할 때 보통 중간 함수가 적절
//매개변수화 하여 넣기
function withinBand(usage,bottom,top){
    return usage > bottom ? Math.min(usage,top) - bottom : 0;
}
function topBand(usage){
    return usage > 200 ? usage - 200 : 0;
}


function baseCharge(usage){
    if(usage < 0) return usd(0);
    const amount = withinBand(usage,0,100) * 0.03
        + withinBand(usage, 100, 200) * 0.05
        + topBand(usage) * 0.07;
    return usd(amount);
}
function topBand(usage){
    return usage > 200 ? usage - 200 : 0;
}


function baseCharge(usage){
    if(usage < 0) return usd(0);
    const amount = withinBand(usage,0,100) * 0.03
        + withinBand(usage, 100, 200) * 0.05
        + withinBand(usage, 200, Infinity) * 0.07;
    return usd(amount);
}

 

+ Recent posts