Study/JavaScript(Clean code)

[JavaScript][clean-code] for문 배열 고차 함수로 리팩터링 & 배열 메서드 체이닝

갈푸라떼 2022. 6. 5. 02:41

* for문 배열 고차 함수로 리팩터링

- 변수 다루기

- 임시변수 줄이기

 

* 예시로 보기

  • 아래의 패턴처럼 사용하는 부분이 많이 있을 것이다.
    • 임시변수를 만들어주고 for문을 이용해 임시변수에 값을 넣어주는 패턴
  • 이럴때는 배열 고차함수를 활용해서 배열문을 조금 더 선언적으로 명시적으로 변경할 수 있다.
const price = ['2000', '1000', '3000', '5000', '4000'];

function getWonPrice(priceList) {
  let temp = [];

  for (let i = 0; i < priceList.length; i++) {
    temp.push(priceList[i] + '원');
  }

  return temp;
}

- 해당 함수는 배열을 조작하는 함수로써 목록을 받아서 suffix를 붙여서 반환해주는 함수이다.

 

* 어떻게 리팩터링하면 좋을까?

  • 고차함수 map을 이용해 리팩터링 할 수 있따.
  • 불필요한 임시변수가 많이 줄어든다.
  • 결과는 동일하게 반환된다.
  • 그리고 추가 요구사항이 생길 경우 좀 더 명시적으로 코드를 추가할 수 있다.
    • ex) 1000원 초과 리스트만 출력, 가격 순 정렬
const price = ['2000', '1000', '3000', '5000', '4000'];

function getWonPrice(priceList) {
  return price.map((price) => price + '원');
}

const result = getWonPrice(price);
console.log(result);

* 추가 요구사항을 처리한 코드

const price = ['2000', '1000', '3000', '5000', '4000'];

const suffixWon = (price) => price + '원' // 원화로 변경
const isOverOneThousand = (price) => Number(price) > 1000 // 1000원 초과 리스트
const ascendingList = (a, b) => a - b; // 오름차순

function getWonPrice(priceList) {
  const isOverList = priceList.filter(isOverOneThousand)
  const sortList = isOverList.sort(ascendingList);

  return sortList.map(suffixWon);
}

const result = getWonPrice(price);
console.log(result);

* 배열 메서드 체이닝을 이용한 좀 더 명확한 코드 (배열 메서드 체이닝 활용)

const price = ['2000', '1000', '3000', '5000', '4000'];

const suffixWon = (price) => price + '원' // 원화로 변경
const isOverOneThousand = (price) => Number(price) > 1000 // 1000원 초과 리스트
const ascendingList = (a, b) => a - b; // 오름차순

function getWonPrice(priceList) {
  return priceList
    .filter(isOverOneThousand) // filter 원하는 조건에 맞는 배열 리스트 만들기
    .sort(ascendingList) // sort 정렬
    .map(suffixWon); // map 배열 요소들을 다시 정리
}

const result = getWonPrice(price);
console.log(result);

1.filter 2.array sort 3.map

  • 명확하게 사용가능
  • for반복문 if문을 사용하기 보단 고차함수를 이용하는것이 더 좋다.
  • 더 명확하고 더 선언적이다.
  • 체이닝을 이용하면 조금 더 명확한 파이프라인 처럼 보인다.

* 만약 위의 코드를 고차함수를 사용하지 않는다면??

const price = ['2000', '1000', '3000', '5000', '4000'];

function getWonPrice(priceList, orderType) {
  let temp = [];

  for (let i = 0; i < priceList.length; i++) {
    if (priceList[i] > 1000) {
      temp.push(priceList[i] + '원')
    }
  }

  if (orderType === 'ASCENDING') {
    someAscendingSortFunc(temp);
  }

  if (orderType === 'DESCENDING') {
    someDescendingSortFunc(temp);
  }

  return temp;
}
  • 결국 로직들이 늘어날수 있다는 아쉬움이 있다.
  • 굉장히 복잡해질 수 있다.