map
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((v) => v.name , products))
filter
const filter = (f, iter) => {
let res = [];
for (const a of iter) {
if (f(a)) {
res.push(a);
}
}
return res;
}
log(filter((v)=>v.price < 20000, products))
reduce
const reduce = (f, acc, iter) => {
if (!iter){
const iter = acc[Symbol.iterator]();
acc = iter.next().value;
}
for (const a of iter ) {
acc = f(acc, a);
}
return acc;
}
const add = (a, b) => a + b;
log(reduce(add, 0, [1,2,3,4,5]))
log(reduce(add, [1,2,3,4,5]))
log(
reduce(add, 0,
filter((a) => a < 20000,
map((a) => a.price, products))
)
)