참조 : https://scotch.io/tutorials/5-tips-to-write-better-conditionals-in-javascript

1, 적응 충첩, 초기 반납

개인적으로 따르는 일반적인 규칙은 무효 조건이 발견 될 때 일찍 반납하는 것 입니다.

/_ return early when invalid conditions found _/

function test(fruit, quantity) {
  const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries'];

  // condition 1: throw error early
  if (!fruit) throw new Error('No fruit!');

  // condition 2: must be red
  if (redFruits.includes(fruit)) {
    console.log('red');

    // condition 3: must be big quantity
    if (quantity > 10) {
      console.log('big quantity');
    }
  }
}

2. 기본 함수 매개 변수 및 분리 사용

// destructing - get name property only
// assign default empty object {}
function test({name} = {}) {
  console.log (name || 'unknown');
}

//test results
test(undefined); // unknown
test({ }); // unknown
test({ name: 'apple', color: 'red' }); // apple

3. Switch 문보다 map / object 리터럴을 좋아한다.

function test(color) {
  // use switch case to find fruits in color
  switch (color) {
    case 'red':
      return ['apple', 'strawberry'];
    case 'yellow':
      return ['banana', 'pineapple'];
    case 'purple':
      return ['grape', 'plum'];
    default:
      return [];
  }
}

//test results
test(null); // []
test('yellow'); // ['banana', 'pineapple']
// use object literal to find fruits in color
  const fruitColor = {
    red: ['apple', 'strawberry'],
    yellow: ['banana', 'pineapple'],
    purple: ['grape', 'plum']
  };

function test(color) {
  return fruitColor[color] || [];
}
// use Map to find fruits in color
  const fruitColor = new Map()
    .set('red', ['apple', 'strawberry'])
    .set('yellow', ['banana', 'pineapple'])
    .set('purple', ['grape', 'plum']);

function test(color) {
  return fruitColor.get(color) || [];
}

4. 전체 / 부분 기준에 Array.every 및 Array.some을 사용합니다.

const fruits = [
    { name: 'apple', color: 'red' },
    { name: 'banana', color: 'yellow' },
    { name: 'grape', color: 'purple' }
  ];

function test() {
  // condition: short way, all fruits must be red
  const isAllRed = fruits.every(f => f.color == 'red');

  console.log(isAllRed); // false
}
const fruits = [
    { name: 'apple', color: 'red' },
    { name: 'banana', color: 'yellow' },
    { name: 'grape', color: 'purple' }
];

function test() {
  // condition: if any fruit is red
  const isAnyRed = fruits.some(f => f.color == 'red');

  console.log(isAnyRed); // true
}


'Back-End > Node' 카테고리의 다른 글

RX 스터디에서 js로 데이터 가공하기 !!  (0) 2018.10.07
company node ver.1  (0) 2018.10.04
swaager  (0) 2018.09.30
Node  (0) 2018.09.28
랜덤한 값 생성  (0) 2018.09.27
Posted by Yuni-Q

블로그 이미지
https://github.com/Yuni-Q/TIL에 정리하기 전 잊지 않기 위해 간단하게 메모해 두는 곳입니다.
Yuni-Q

태그목록

공지사항

Yesterday
Today
Total

달력

 « |  » 2025.8
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31

최근에 올라온 글

최근에 달린 댓글

글 보관함