[JavaScript ES6+] map, filter, reduce


あらかじめ準備する



1. map


データから名前を抽出する場合
// 명령형 코드
// 이름만 빼내기
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));

2.異機種プロトコルのマッピングに従う多形性

log(document.querySelectorAll('*').map);  // -> undefined
document.QuerySelector Allは配列を継承するオブジェクトではないため、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)));

3. filter

// 명령형 코드
let under20000 = [];
for (const p of products) {
    if (p.price < 20000) under20000.push(p);
}
log(...under20000);
他の条件を作成する場合は、コードをコピーする必要があります.これにより、不要な重複が発生します.
フィルターで再包装します.
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;
}()));

4. reduce


reduce:小さな値を収縮する関数

基本用法1

const reduce = () => {

};

log(reduce());

基本用法2

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());
reduceを使用して製品のすべての価格を実現するだけです.
log(reduce(
    (total_price, product) =>
      total_price + product.price, 0, products));

5.map+filter+reduce重畳と関数式思考を用いる


-fxを予め用意します。jsファイルの作成



れんどう

<script src="../lib/fx.js"></script>

20,000ウォン未満の商品の価格をすべて加算します

const add = (a, b) => a + b;

log( //출력할거야
    reduce( //값을 함수에 넣어서 축약할건데
        add, //그 함수는 add이고 값은 데이터에서 추출(map)해낼거야
        map(p => p.price, //뭘 추출할거냐면 가격
            filter(p => p.price < 20000, products)))); //근데 가격이 20000원 미만인 것을 필터링할거야

20,000ウォン以上の商品の価格を加算します

log(
    reduce(
        add,
        filter(n => n >= 20000,
            map(p => p.price, products))));