3장 특수한 컬렉션을 이용해 코드 명료성을 극대화하라

설아아빠·2021년 12월 24일
0
post-thumbnail

1. 객체를 이용해 정적인 키-값을 탐색하라

2. Object.assign()으로 조작없이 객체를 생성하라

        const defaults = {
            author: '',
            title: 'test'
        };

        const book = {
            author: 'me',
            title: 'zz'
        }

        const n = Object.assign({}, defaults, book);

        console.log(n, defaults, book);

3. 객체 펼침 연산자로 정보를 갱신하라

        const book = {
            name: 'book',
            price: 100,
            etc: {
                p1: 1,
                p2: 2
            }
        }

        const newBook = {...{}, ...book, author: 'tester', name: '1234'};
        console.log(newBook, book);

4. 맵으로 명확하게 키-값 데이터를 갱신하라

        const data = new Map([
            ['견종', '도베르만']
        ]);

        data.set('색상', '검은색');

        console.log(data, data.get('견종'));

        data.delete('견종');

        console.log(data, data.get('견종'));

5. 맵과 펼침 연산자로 키-값 데이터를 순회하라

        const data = [{
            order: 3,
            name: 'c'
        }, {
            order: 2,
            name: 'b'
        }, {
            order: 1,
            name: 'a'
        }];

        function sortedData() {
            const result = [...data];

            return result
                .sort((a, b) => a.order - b.order)
                .map((o, idx) => {
                    return o.name;
                })
                .join(',');
        }

        const v = sortedData();

        console.log(v);

6. 맵 생성 시 부수 효과를 피하라

        function changedData(map, defaults) {
            return new Map([...defaults, ...map]);
        }

        const v = changedData([['name', 'test']], [['name', 'test2'], ['age', 65]]);

        console.log(v);

7. 세트를 이용해 고윳값을 관리하라

        const dogs = [
            {name: '맥스', color: 'red'},
            {name: '톰', color: 'yellow'},
            {name: '제리', color: 'blue'},
            {name: '바보', color: 'red'},
        ];

        //색상 가저오기
        const colors = dogs.map(dog => dog.color);
        console.log(colors);

        //유니크한 색상 목록 뽑아오기 (나는 이게 더 좋아보임...)
        const uniqueColors = [...new Set(dogs.map(dog => dog.color))];
        console.log(uniqueColors);

        //reduce로 변경하기
        const uniqueColorsByReduce = [...dogs.reduce((colors, {color}) => colors.add(color), new Set())];
        console.log(uniqueColorsByReduce);
profile
back-end(java), front-end (조금)

0개의 댓글