zoukankan      html  css  js  c++  java
  • [Javascript] Compare a Generator to Using Array Map and Filter

    Generators offer flexible alternatives to working with arrays and how you want to iterate through the data. While most scenarios are covered by the methods included on Arrays such as "map" and "filter", generators are great for covering complex scenarios when writing all your logic in map and filter functions might become difficult.

    let names = ["John", "Mindy", "Sally"]
    
    let result = names.filter(name => name.includes("y")).map(name => name.toLocaleLowerCase())
    console.log(result) // ["mindy", "sally"]
    
    // -- Generator --
    
    function* format(array: string[]) {
        for (let name of array) {
            if (name.includes("y")) {
                yield name.toLowerCase();
            }
        }
    }
    
    console.log([...format(names)]); //["mindy", "sally"]

    With Generator, we can do more control on result.

    let names = ["John", "Mindy", "Sally"]
    
    let result = names.filter(name => name.includes("y")).map(name => name.toLocaleLowerCase())
    console.log(result) // ["mindy", "sally"]
    
    // -- Generator --
    
    function* format(array: string[]) {
        for (let name of array) {
            if (name.includes("y")) {
                yield name.toLowerCase(); // ["mindy", "sally"]
                yield name.toUpperCase(); // ["mindy", "MINDY", "sally", "SALLY"]
                yield* array; // ["mindy", "MINDY", "John", "Mindy", "Sally", "sally", "SALLY", "John", "Mindy", "Sally"]
                yield 'END'; // ["mindy", "MINDY", "John", "Mindy", "Sally", "END", "sally", "SALLY", "John", "Mindy", "Sally", "END"]
            }
        }
    }
    
    console.log([...format(names)]);
  • 相关阅读:
    【中山纪念中学六年级模拟赛】方格翻转 题解
    高斯消元
    net 控件开发资料
    使用自定义验证组件库扩展 Windows 窗体
    POJ 3032
    UVa 10878 Decode the tape
    C语言I博客作业03
    第十周助教总结
    第十二周助教总结
    C语言I博客作业06
  • 原文地址:https://www.cnblogs.com/Answer1215/p/12168027.html
Copyright © 2011-2022 走看看