码迷,mamicode.com
首页 > 编程语言 > 详细

[Javascript] Compare a Generator to Using Array Map and Filter

时间:2020-01-08 19:22:47      阅读:98      评论:0      收藏:0      [点我收藏+]

标签:gre   tin   include   mos   fun   function   name   locale   console   

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)]);

 

[Javascript] Compare a Generator to Using Array Map and Filter

标签:gre   tin   include   mos   fun   function   name   locale   console   

原文地址:https://www.cnblogs.com/Answer1215/p/12168027.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!