본문 바로가기

Javascript/Clean Code

6.배열다루기 - 2 (for 문 배열 고차 함수로 리팩터링, 배열 메서드 체이닝 활용하기, map vs forEach, continue & break)

■ 순서

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

7.배열 메서드 체이닝 활용하기

8.map vs forEach

9.continue & break


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

: 아래의 for문은 고차함수로 바꾸면 간단하게 바꿔줄수가 있다.

 

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

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

  return temp
}


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

 

그다음에 1000원 초과 리스트만 출력을 해보자. if문을 변경

const suffixWon = (price) => price + '원';
const isOverOneThousand = (price) => Number(price) > 1000;

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

  return isOverList.map(suffixWon);
}

 

 

그 다음으로 정렬까지 해본다면 아래와 같이 해볼 수 있다.

const suffixWon = (price) => price + '원';
const isOverOneThousand = (price) => Number(price) > 1000;
const ascendingList = (a, b) => a - b;

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

  return sortList.map(suffixWon);
}

7.배열 메서드 체이닝 활용하기

: 위와 같이 고차함수로 리팩터링을 했지만, 계속적으로 고차함수가 늘어나는 것도 부담이 될수가 있다.

: 이 경우에 메서드 체이닝을 활용해서 개선을 하면 좋다.

const suffixWon = (price) => price + '원';
const isOverOneThousand = (price) => Number(price) > 1000;
const ascendingList = (a, b) => a - b;

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

  return sortList.map(suffixWon);
}


//이 부분은 아래와 같이 바꿀수가 있다.

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

8.map vs forEach

: map과 forEach는 자주 헷 갈릴수가 있다.

두개의 차이는 return의 차이로 구별을 할 수가 있다.

 

forEach의 반환값은 undefined다. 매 요소마다 함수를 실행시켜주는 것이 전부이다.

map은 반환되는 값이 각각 요소마다 실행되고 각각 실행될 때마다 실행한 요소들을 변경한다.

 

아래의 예제는 둘다 동일한 값이 표시가 되고 있다.

map은 새로운 함수를 만들기 때문에 필요한 경우에 사용하는 것이 좋다.

const prices = ['1000', '2000', '3000'];

const newPricesForEach = prices.forEach((price) => price + '원');
const newPricesMap = prices.map((price) => price + '원');

9.continue & break

: 위의 고차함수는 배열 중간에 흐름을 제어하기가 어렵다.

아래와 같이 continue와 break로 우리가 원하는 대로 해당되는 값이 들어왔을때 건너띄거나 멈추고 싶지만,

이런 경우에 문법에러가 나온다. 자바스크립트 문법상 오류이다.

const orders = ['first', 'second', 'third'];

const orders.forEach(function(order) {
  if(order === 'second') {
    break;
  }
  
  console.log(order);
});

 

그래서 이럴때는 try catch를 쓰는게 더 좋다.

const orders = ['first', 'second', 'third'];


try {
  orders.forEach(function(order) {
  
    if(order === 'second') {
      throw n/a
    }
  
    console.log(order);
  });
  } catch (e) {
  
  }

 

또한 이런 것을 제어할때는 다시 for문을 사용하는 게 좋다.

또 다른 방법으로는 아래와 같은 방법을 사용한다.(다른 배열 메소드와의 조합)

 

Array.prototype.every() //every는 모두가 조건이 성립되야 됨(and)

Array.prototype.some() //some은 or 과 같이

Array.prototype.find()  //발견이 되었을때

Array.prototype.findIndex()