Study/JavaScript(Clean code)

[JavaScript][clean-code] 배열 요소에 접근하기(구조 분해 할당)

갈푸라떼 2022. 6. 1. 16:48

* 배열 요소에 접근하기

- 배열에 있는 하나하나의 단위들을 요소라고 한다.

 

* 배열 요소 접근 예시

const array = [1, 2, 3]


function operateTime(input, operators, is) {
  inputs[0].split('').forEach((num) => {
    cy.get('.digit').contains(num).click();
  });

  inputs[1].split('').forEach((num) => {
    cy.get('.digit').contains(num).click();
  });
}
  • 배열의 요소를 index번호 [0], [1]으로 출력을 하고있어서 어떤요소가 담겨있는지 예측이 되지 않는다.
  • 가독성이 떨어진다.
  • 배열 요소에 좀 더 명확하게 접근할 필요성이 있다.

* 구조 분해 할당을 이용한 요소 접근

function operateTime(input, operators, is) {
  const [firstInput, secondInput] = input

  firstInput.split('').forEach((num) => {
    cy.get('.digit').contains(num).click();
  });

  secondInput.split('').forEach((num) => {
    cy.get('.digit').contains(num).click();
  });
}

* 매개변수에 배열을 넣어버리기

function operateTime([firstInput, secondInput], operators, is) {
  fitstInput.split('').forEach((num) => {
    cy.get('.digit').contains(num).click();
  });

  secondInput.split('').forEach((num) => {
    cy.get('.digit').contains(num).click();
  });
}

operateTime([1, 2], 1, 2)

* 두번째 예시

function clickGroupButton() {
  const confirmButton = document.getElementsByTagName('button')[0];
  const cancelButton = document.getElementsByTagName('button')[1];
  const resetButton = document.getElementsByTagName('button')[2];

  // ... some code
}
function clickGroupButton() {
  const [confirmButton, cancelButton, resetButton] = document.getElementsByTagName('button');
  // ... some code
}
  • 구조 분해 할당을 이용해 축약
  • 역할에 대해서 굉장히 명시적이다.

* 세번째 예시

function formatData(targetDate) {
  const date = targetDate.toISOString().split('T')[0];

  const [year, month, day] = date.split('-');

  return `${year}년 ${month}월 ${day}일`;
}
function formatData(targetDate) {
  const [date] = targetDate.toISOString().split('T');

  const [year, month, day] = date.split('-');

  return `${year}년 ${month}월 ${day}일`;
}
  • 구조 분해 할당 사용
  • 하나를 분해 할 때도 사용할 수 있다.

* 구조분해할당이 불편하면 유틸함수를 만들면된다.

  • Lodash | _.head() Method 처럼 유틸 함수를 만든다.
  • _.head(array)
  • Gets the first element of array.
_.head([1, 2, 3]); // 1
_.head([]); // undefined

* 직접 유틸 함수를 만드는 예시

  • head라는 함수를 만든다. 인자로 받은 배열의 0번째 인덱스를 출력하고 빈값을 받으면 ' '를 반환한다.
  • nullish coalescing operator와 같이 사용
function head(arr) {
  return arr[0] ?? '';
}

function formatData(targetDate) {
  const date = head(targetDate.toISOString().split('T'))

  const [year, month, day] = date.split('-');

  return `${year}년 ${month}월 ${day}일`;
}