이터레이터 사용: 고차 함수 > 루프 for-in / for-of
Don't use iterators. Prefer JavaScript's higher-order functions like map() and reduce() instead of loops like
- 이터레이터를 사용하지 마세요. for-in이나 for-of 같은 루프 대신 자바스크립트의 고급함수를 사용한다.
- 고차 함수
- 불변 규칙을 강제하기 위함이다.
- 값을 리턴하는 순수 함수를 다루는 것이 더 쉽기 때문에 사이드 이펙트도 작을 수 있음.
- 배열 순회
- map()
- every()
- filter()
- find()
- findIndex()
- reduce()
- some() / ...
- 객체 -> 배열
- Object.keys()
- Object.values()
- Object.entries()
- 고차 함수
const numbers = [1, 2, 3, 4, 5];
// bad
let sum = 0;
for (let num of numbers) {
sum += num;
}
sum === 15;
// good
let sum = 0;
numbers.forEach((num) => {
sum += num;
});
sum === 15;
// best (use the functional force)
const sum = numbers.reduce((total, num) => total + num, 0);
sum === 15;
// bad
const increasedByOne = [];
for (let i = 0; i < numbers.length; i++) {
increasedByOne.push(numbers[i] + 1);
}
// good
const increasedByOne = [];
numbers.forEach((num) => {
increasedByOne.push(num + 1);
});
// best (keeping it functional)
const increasedByOne = numbers.map(num => num + 1);
현재 제너레이터는 ES5 트랜스파일링이 잘 되지 않는다.
Don't use generators for now.
제너레이터의 * 연산자의 적절한 공백 : function* foo()
function
,*
-> 같은 개념적 키워드 이다.*
는 함수에 대한 수정자가 아님- function
*
은 함수와 다른 고유 한 구성(구조)이다.
// bad
function * foo() {
// ...
}
// bad
const bar = function * () {
// ...
};
// bad
const baz = function *() {
// ...
};
// bad
const quux = function*() {
// ...
};
// bad
function*foo() {
// ...
}
// bad
function *foo() {
// ...
}
// very bad
function
*
foo() {
// ...
}
// very bad
const wat = function
*
() {
// ...
};
// good
function* foo() {
// ...
}
// good
const foo = function* () {
// ...
};
'JS > 자바스크립트 Style Guide' 카테고리의 다른 글
12. Variables (JS style guide) (0) | 2023.01.26 |
---|---|
11. Properties (JS style guide) (2) | 2023.01.16 |
9. Modules(JS style guide) (0) | 2023.01.03 |
8. Classes & Constructors(JS style guide) (0) | 2022.12.27 |
7. Arrow Functions (JS style guide) (0) | 2022.12.21 |