본문 바로가기
Javascript

[JS] JS 5가지 팁

by F.E.D 2019. 2. 1.

[JS] JS 5가지 팁

1. Array.includes 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// condition
function test(fruit) {
  if (fruit == 'apple' || fruit == 'strawberry') { // 다른 과일이 늘어나면??????
    console.log('red');
  }
}

// using Array.includes
function test(fruit) {
  // extract conditions to array
  const redFruits = ['apple''strawberry''cherry''cranberries'];
  if (redFruits.includes(fruit)) {
    console.log('red');
  }
}
cs


2. Less Nesting, Return Early

위의 예제에서 2가지 조건을 추가합니다.


* 과일이 제공되지 않으면 오류가 발생합니다. 

* 열매량을 받아들이고 10을 초과하는 경우 로그를 찍습니다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
function test(fruit, quantity) {
  const redFruits = ['apple''strawberry''cherry''cranberries'];
 
  // condition 1: fruit must has value
  if (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');
      }
    }
  } else {
    throw new Error('No fruit!');
  }
}
 
// test results
test(null); // error: No fruits
test('apple'); // print: red
test('apple'20); // print: red, big quantity
cs


* 유효하지 않은 조건을 필터링하는 if/else문 

* 중첩 된 if 문 (조건 1, 2 및 3)의 3 가지 수준


하지만 여기서 더 나아가서 자원을 반납할 필요가 있을 때 빨리 반납하는 것이 중요합니다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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');
    }
  }
}
cs


이렇게하면 중첩 된 문장이 한 단계 줄어 듭니다. 

이 코딩 스타일은 특히 긴 if문을 사용할 때 좋습니다.


조건을 반전하고 조기에 반환하면 중첩을 더 줄일 수 있습니다


1
2
3
4
5
6
7
8
9
10
11
12
13
function test(fruit, quantity) {
  const redFruits = ['apple''strawberry''cherry''cranberries'];
 
  if (!fruit) throw new Error('No fruit!'); // condition 1: throw error early
  if (!redFruits.includes(fruit)) return// condition 2: stop when fruit is not red
 
  console.log('red');
 
  // condition 3: must be big quantity
  if (quantity > 10) {
    console.log('big quantity');
  }
}
cs


조건 2의 조건을 반대로하면 코드에 중첩 된 문장이 없어집니다. 

이 기술은 우리가 갈 길이 멀고 조건이 충족되지 않을 때 추가 프로세스를 중단하고자 할 때 유용합니다.


따라서 항상 적은 중첩 및 초기 반환을 목표로하지만 과용하지는 않습니다. 


기본 함수 매개 변수 및 Destructuring 사용

1
2
3
4
5
6
7
8
9
10
function test(fruit, quantity) {
  if (!fruit) return;
  const q = quantity || 1// if quantity not provided, default to one
 
  console.log(`We have ${q} ${fruit}!`);
}
 
//test results
test('banana'); // We have 1 banana!
test('apple'2); // We have 2 apple!
cs

사실, 우리는 디폴트 함수 매개 변수를 할당함으로써 변수 q를 제거 할 수 있습니다.



1
2
3
4
5
6
7
8
function test(fruit, quantity = 1) { // if quantity not provided, default to one
  if (!fruit) return;
  console.log(`We have ${quantity} ${fruit}!`);
}
 
//test results
test('banana'); // We have 1 banana!
test('apple'2); // We have 2 apple!
cs


훨씬 쉽고 직관적이지 않습니까? 각 매개 변수에는 자체 기본 함수 매개 변수가있을 수 있습니다. 

예를 들어 fruit에 기본값을 지정할 수도 있습니다 

function test (fruit = 'unknown', quantity = 1).


1
2
3
4
5
6
7
8
9
10
11
12
13
function test(fruit) { 
  // printing fruit name if value provided
  if (fruit && fruit.name)  {
    console.log (fruit.name);
  } else {
    console.log('unknown');
  }
}
 
//test results
test(undefined); // unknown
test({ }); // unknown
test({ name: 'apple', color: 'red' }); // apple
cs


1
2
3
4
5
6
7
8
9
10
// 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

cs


다음은 Lodash를 사용하는 예입니다. (3rd party)


1
2
3
4
5
6
7
8
9
// Include lodash library, you will get _
function test(fruit) {
// get property name, 
//if not available, assign default value 'unknown'
  console.log(__.get(fruit, 'name''unknown'); 
}
 
//test results
test(undefined); // unknown
test({ }); // unknown
test({ name: 'apple', color: 'red' }); // apple
cs


Favor Map / Object Literal than Switch Statement

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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']
cs


위의 코드는 아무 문제가없는 것처럼 보이지만, 매우 장황하다. 더 똑똑한 구문을 사용하여 객체 리터럴에서도 동일한 결과를 얻을 수 있습니다.


1
2
3
4
5
6
7
8
9
10
// 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] || [];
}
cs


또는 MAP을 사용하여 동일한 결과를 얻을 수도 있습니다.


1
2
3
4
5
6
7
8
9
// 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) || [];
}
cs


위의 예제에서 Array.filter를 사용하여 동일한 결과를 얻으려면 코드를 실제로 리팩터링 할 수 있습니다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
 const fruits = [
    { name: 'apple', color: 'red' }, 
    { name: 'strawberry', color: 'red' }, 
    { name: 'banana', color: 'yellow' }, 
    { name: 'pineapple', color: 'yellow' }, 
    { name: 'grape', color: 'purple' }, 
    { name: 'plum', color: 'purple' }
];
 
function test(color) {
  // use Array filter to find fruits in color
  return fruits.filter(f => f.color == color);
}

cs


동일한 결과를 얻으려면 항상 1가지 이상의 방법이 있습니다. 

우리는 같은 예를 가지고 4가지를 보았습니다. 


Use Array.every & Array.some for All / Partial Criteria

이 마지막 팁은 코드 라인을 줄이기 위해 Javascript Array (Javascript Array) 기능을 새로 도입 한 것입니다. 
아래 코드를 살펴보면 모든 과일이 붉은색으로되어 있는지 확인하고자합니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
const fruits = [
    { name: 'apple', color: 'red' },
    { name: 'banana', color: 'yellow' },
    { name: 'grape', color: 'purple' }
  ];
 
function test() {
  let isAllRed = true;
 
  // condition: all fruits must be red
  for (let f of fruits) {
    if (!isAllRed) break;
    isAllRed = (f.color == 'red');
  }
 
  console.log(isAllRed); // false
}
cs

코드가 너무 길어! 우리는 Array.every를 사용하여 줄 수를 줄일 수 있습니다.


1
2
3
4
5
6
7
8
9
10
11
12
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
}
cs


비슷한 방법으로 과일이 빨간색인지 테스트하고 싶다면 Array.some을 사용하여 한 줄로 완성 할 수 있습니다.


1
2
3
4
5
6
7
8
9
10
11
12
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
}

cs






출처 : https://scotch.io/tutorials/5-tips-to-write-better-conditionals-in-javascript#toc-1-use-array-includes-for-multiple-criteria

'Javascript' 카테고리의 다른 글

Javscript Callback  (0) 2019.09.12
Javascript 함수가 왜 1급 객체일까?  (0) 2019.09.12
[JS] Reducer?  (0) 2019.01.27
[JS] IOS의 CLICK 버블링이 발생하지 않아요  (0) 2019.01.27
[JS] GITHUB이 Jquery를 삭제하다  (0) 2019.01.26

댓글