reduce

이효범·2022년 4월 5일
0

ES6 - OOP & FRP

목록 보기
6/15
post-thumbnail

Array는 Array Class의 인스턴스이다. 따라서 Array Class에 정의되어 있는 메소드들을 활용할 수 있다. 주인장은 Array의 헬퍼 메소드들을 통해 OOP와 FRP의 기초에 대해 공부해보려 한다.

reduce

array helper methods 중에서 마지막으로 알아볼 reduce이다.
첫번째 예시를 보자.

let numbers = [1, 2, 3, 4, 5];
let sum = 0;

// imperative
for (let i = 0; i < numbers.length; i++) {
    sum += numbers[i];
}
console.log(sum);  // 15

// declarative
sum = numbers.reduce(function (a, b) {
    return a + b;
}, 0);
console.log(sum);  // 15

두번째 예시를 보자.

let heroes = [
    { balance: 5000, id: 1, name: 'superman', type: 'Flying', cost: 400 },
    { balance: 7000, id: 2, name: 'batman', type: 'Flying', cost: 320 },
    { balance: 9000, id: 11, name: 'batman', type: 'Flying', cost: 320 },
    { balance: 3000, id: 3, name: 'X-man', type: 'Mutant', cost: 200 },
    { balance: 1000, id: 4, name: 'Ironman', type: 'Metal', cost: 530 },
    { balance: 6000, id: 5, name: 'Antman', type: 'Insect', cost: 180 },
];

// heroes라는 array에서 name만 뽑아서 보고 싶다면 어떻게 할 것인가
// ['superman', 'batman', ...]
// 이럴 경우에도 reduce를 쓸 수 있다.

let heroNames = heroes.reduce(function (accumulator, hero) {
    accumulator.push(hero.name);
    return accumulator;
}, []);
console.log(heroNames); // ['superman', 'batman', ...]

reduce를 통해 이름만 뽑아서 하나의 별도의 array를 구성할 수 있다.

reduce 연습

1. 첫번째 연습문제
reduce를 이용한 퀴즈이다.

// Implement the below function
function balancedParens() {}

balancedParens('()))'); // False
balancedParens('((()))'); // True

balancedParens함수에 인자로 괄호가 들어있는 문자열을 던져줬을 때 열리는 괄호와 닫히는 괄호가 서로 대칭이라면 true를 반환하고 반대라면 false를 반환해야한다.

// Implement the below function
function balancedParens(string) {
    return !string.split('').reduce(function (acc, char) {
      	if (acc < 0) return acc;
        if (char === '(') return ++acc;
        if (char === ')') return --acc;
        return acc;
    }, 0);
}

2. 두번째 연습문제
reduce를 이용해서 다음 문제를 풀어보자.

// 1. Use the 'reduce' helper to find the sum of all the distances traveled.
const trips = [{ distance: 34 }, { distance: 12 }, { distance: 15 }];

let totalDistance;

reduce를 이용해서 위 distance의 값들을 모두 더해보자.

let totalDistance = trips.reduce(function (prev, trip) {
    return prev + trip.distance;
}, 0);

console.log(totalDistance);

3. 세번째 연습문제
reduce를 이용해서 다음 문제를 풀어보자.

// 2. Use the 'reduce' and 'find' helper to create an object
// that tallies the number of a specific type. ex) '{flying: 3, running: 2}'.
const heroes = [
    { name: 'superman', type: 'flying' },
    { name: 'batman', type: 'flying' },
    { name: 'batman', type: 'running' },
    { name: 'X-man', type: 'running' },
    { name: 'Ironman', type: 'flying' },
];

let types;

reduce를 이용해서 위 heroes의 type의 종류를 분류해보자.

// 첫 번째 풀이
let types = heroes.reduce(function (prev, hero) {
    hero.type === 'flying' ? prev.flying++ : prev.running++;
    return prev;
},{ flying: 0, running: 0 });

// 두 번째 풀이
let types = heroes.reduce(function (prev, hero) {
    prev[hero.type]++;
    return prev;
},{ flying: 0, running: 0 });

console.log(types);  // {flying: 3, running: 2}

4. 네번째 연습문제
reduce를 이용해서 다음 문제를 풀어보자.

// 3. Implement function unique(array) using the 'reduce' helper.
const nubers = [1, 1, 2, 3, 4, 4];

let unique;

reduce를 이용해서 위 nubers의 배열을 중복값이 없는 새로운 배열을 만들어보자.
Set을 이용하면 간편하긴 하다만 우리는 reduce를 연습 중이니, 한번 해보자.

let unique = numbers.reduce(function (prev, number) {
    prev.includes(number) ? prev : prev.push(number);
    return prev;
}, []);

console.log(unique);  // [1, 2, 3, 4]
profile
I'm on Wave, I'm on the Vibe.

0개의 댓글