1. 배열로 유연한 컬렉션을 생성하라
const team = ['b', 'a', 'c', 'd'];
function sortedTeam() {
return [...team].sort();
}
console.log(team, sortedTeam(), team);
const staff = [{
name: '홍길동',
position: '음악가'
}, {
name: '김갑수',
position: '예술가'
}];
function getMusicians() {
return staff.filter(member => member.position === '음악가');
}
console.log(getMusicians());
const sections = ['aaa', 'bbb', 'cccc', 'cccbbb'];
console.log(sections.filter(member => member.includes('bbb')));
2. 펼침 연산자로 배열을 본떠라
const list = ['a1', '2', '3', '4', '5'];
const removeItem = idx => {
return [...list.slice(0, idx), ...list.slice(idx + 1)];
};
const removed = removeItem(4);
console.log(list, removed);
3. push() 메서드 대신 펼침 연산자로 원본 변경을 피하라
const cart = [{
name: 'test1',
price: 100
}, {
name: 'test2',
price: 200
}];
const reward = {
name: 'test3',
price: 300,
discount: true
}
function getCartWithReward() {
return [...cart, reward];
}
function summarizeCart() {
const cartWithReward = getCartWithReward();
const disCountAble = cartWithReward.filter(product => product.discount);
if (disCountAble.length > 1) {
return {
error: '할인상품은 하나만 주문할 수 있습니다'
}
}
return cartWithReward;
}
console.log(summarizeCart());
4. 펼침 연산자로 정렬에 의한 혼란을 피하라
const staff = [{
name: 'test1',
age: 11
}, {
name: 'test2',
age: 21
}, {
name: 'test3',
age: 16
}];
const sorted = [...staff].sort((a, b) => a.age - b.age);
console.log(sorted);