How can I perform operations in JavaScript just like we do pipeline of operations in Java streams?

前端 未结 7 1082
北海茫月
北海茫月 2020-12-18 20:07

In Java 8 using streams when I chain methods one after the another the execution of operations are performed in pipelined manner.

Example:

List

        
7条回答
  •  感情败类
    2020-12-18 20:25

    The equivalent to Java's streams are JavaScript's iterators. Iterator objects unfortunately don't have a map method (yet), but you can easily write one yourself (and even install it on the prototype if you want method syntax).

    function* map(iterable, f) {
        for (var x of iterable)
            yield f(x);
    }
    
    var nums = [1,2,3,4,5,6];
    function square(x) {
      x = (x * x);
      console.log('map1='+x);
      return x;
    }
    function triple(x) {
      x = x * 3;
      console.log('map2='+x);
      return x;
    }
    for (const x of map(map(nums.values(), square), triple)) {
      console.log('forEach='+x);
    }

    Also notice that in functional programming, order doesn't matter for pure operations - you shouldn't need to rely on the execution order if you are using map.

提交回复
热议问题