๋ฐ์ดํฐ์์ ์ด๋ฆ์ ์ถ์ถํ ๋
// ๋ช
๋ นํ ์ฝ๋
// ์ด๋ฆ๋ง ๋นผ๋ด๊ธฐ
let names = [];
for (const p of products) {
names.push(p.name);
}
log(names);
๋ฐ์ดํฐ์์ ๋์ด๋ฅผ ๊ฐ๊ฒฉ์ ์ถ์ถํ ๋
let prices = [];
for (const p of products) {
names.push(p.price);
}
log(prices);
๐๐ป ๋ถํ์ํ ์ค๋ณต์ด ๋ฐ์ํ๋ค.
์ด๋ด ๋ ์ฌ์ฉํ๋ ๊ฒ์ด map
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));
log(document.querySelectorAll('*').map); // -> undefined
document.querySelectorAll์ array๋ฅผ ์์๋ฐ์ ๊ฐ์ฒด๊ฐ ์๋๋ผ์ prototype์ mapํจ์๊ฐ ๊ตฌํ์ด ์๋์ด์์
log([1, 2, 3].map(a => a + 1));
log(map(el => el.nodeName, document.querySelectorAll('*')));
const it = document.querySelectorAll('*')[Symbol.iterator]();
log(it.next());
log(it.next());
log(it.next());
log(it.next());
log(it.next());
function *gen() { //์ ๋๋ ์ดํฐ ์์ฑ
yield 2;
if (false) yield 3;
yield 4;
}
log(map(a => a * a, gen()));
let m = new Map();
m.set('a', 10);
m.set('b', 20);
log(new Map(map(([k, a]) => [k, a * 2], m)));
// ๋ช
๋ นํ ์ฝ๋
let under20000 = [];
for (const p of products) {
if (p.price < 20000) under20000.push(p);
}
log(...under20000);
๋ค๋ฅธ ์กฐ๊ฑด์ ๋ง๋๋ ค๋ฉด ์ฝ๋ ๋ณต์ฌํด์ผ ๋์ ๋ถํ์ํ ์ค๋ณต์ด ๋ฐ์ํ๋ฏ๋ก
filter๋ก ๋ฆฌํฉํ ๋ง ํ๋ค.
const filter = (f, iter) => { //f๊ฐ ํจ์์(๊ฑธ๋ฌ๋ผ ์กฐ๊ฑด!)
let res = [];
for (const a of iter) {
if (f(a)) res.push(a);
}
return res;
};
log(...filter(p => p.price < 20000, products));
log(...filter(p => p.price >= 20000, products));
log(filter(n => n % 2, [1, 2, 3, 4]));
log(filter(n => n % 2, function* () {
yield 1;
yield 2;
yield 3;
yield 4;
yield 5;
}()));
reduce : ์ดํฐ๋ฌ๋ธ ๊ฐ์ ์ถ์ฝํ๋ ํจ์
const reduce = () => {
};
log(reduce());
const add = (a, b) => a + b;
log(reduce(add, 0, [1, 2, 3, 4, 5])); // -> 15
log(add(add(add(add(add(0, 1), 2), 3), 4), 5)); // -> 15
log(reduce(add, [1, 2, 3, 4, 5])); // -> 15
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());
products์ ๋ชจ๋ price๋ฅผ ๋ํ๋ ๊ฒ์ reduce๋ง ์จ์ ๊ตฌํํ๋ฉด
log(reduce(
(total_price, product) =>
total_price + product.price, 0, products));
<script src="../lib/fx.js"></script>
const add = (a, b) => a + b;
log( //์ถ๋ ฅํ ๊ฑฐ์ผ
reduce( //๊ฐ์ ํจ์์ ๋ฃ์ด์ ์ถ์ฝํ ๊ฑด๋ฐ
add, //๊ทธ ํจ์๋ add์ด๊ณ ๊ฐ์ ๋ฐ์ดํฐ์์ ์ถ์ถ(map)ํด๋ผ๊ฑฐ์ผ
map(p => p.price, //๋ญ ์ถ์ถํ ๊ฑฐ๋๋ฉด ๊ฐ๊ฒฉ
filter(p => p.price < 20000, products)))); //๊ทผ๋ฐ ๊ฐ๊ฒฉ์ด 20000์ ๋ฏธ๋ง์ธ ๊ฒ์ ํํฐ๋งํ ๊ฑฐ์ผ
log(
reduce(
add,
filter(n => n >= 20000,
map(p => p.price, products))));