1. map
- map() 메서드는 배열 내의 모든 요소 각각에 대하여 주어진 함수를 호출한 결과를 모아 새로운 배열을 반환한다.
const arr = [1,2,3]
log(arr.map(a => a + 1));
const products = [
{name: '반팔티', price: 15000},
{name: '긴팔티', price: 20000},
{name: '핸드폰케이스', price: 15000},
{name: '후드티', price: 30000},
{name: '바지', price: 25000}
];
log(products.map(p => p.name));
(3) [2, 3, 4]
(5) ['반팔티', '긴팔티', '핸드폰케이스', '후드티', '바지']
1-1. 이터러블 프로토콜을 따른 map의 다형성
const log = console.log;
const products = [
{name: '반팔티', price: 15000},
{name: '긴팔티', price: 20000},
{name: '핸드폰케이스', price: 15000},
{name: '후드티', price: 30000},
{name: '바지', price: 25000}
];
const map = (f, iter) => {
let res = [];
for (const a of iter) {
res.push(f(a));
}
return res;
};
log(map(p => p.name, products));
log(map(p => p.price, products));
- 함수와 이터러블 프로토콜을 따르는 객체를 인자로 받는 map 메서드를 새로 지정했다.
let m = new Map();
m.set('a', 10);
m.set('b', 20);
log(map(([k, a]) => [k, a * 2], m));
log(new Map(map(([k, a]) => [k, a * 2], m))); b
[ [ 'a', 20 ], [ 'b', 40 ] ]
Map(2) { 'a' => 20, 'b' => 40 }
2. filter
- filter() 메서드는 주어진 함수의 테스트를 통과하는 모든 요소를 모아 새로운 배열로 반환한다.
const filter = (f, iter) => {
let res = [];
for (const a of iter) {
if (f(a)) res.push(a);
}
return res;
};
log(...filter(p => p.price < 20000, products));
{name: '반팔티', price: 15000}
{name: '핸드폰케이스', price: 15000}
3. reduce
- reduce 메서드는 배열의 각 요소에 대해 주어진 리듀서(reducer) 함수를 실행하고, 하나의 결과값을 반환합니다.
const reduce = (f, acc, iter) => {
if (!iter) {
iter = acc[Symbol.iterator]();
acc = iter.next().value;
}
for (const a of iter) {
acc = f(acc, a);
}
return acc;
};
log(reduce(add, 0, [1, 2, 3, 4, 5]));
log(add(add(add(add(add(0, 1), 2), 3), 4), 5));
log(reduce(add, [1, 2, 3, 4, 5]));
4. 2만원 이하의 제품의 총 금액을 구하시오.
const products = [
{name: '반팔티', price: 15000},
{name: '긴팔티', price: 20000},
{name: '핸드폰케이스', price: 15000},
{name: '후드티', price: 30000},
{name: '바지', price: 25000}
];
const add = (a, b) => a + b;
log(
reduce(
add,
map(p => p.price,
filter(p => p.price <= 20000, products))));
log(
reduce(
add,
filter(n => n >= 20000,
map(p => p.price, products))));