头图

Test code:

fromEvent(this.test, 'click').pipe(map( event => event.timeStamp), mapTo(1)).subscribe((event) => console.log(event));

Two input operations of the pipe operation:

The input parameter is an array containing two elements:

Using the original Observable as input, perform these two operations:

The reduce of an array is a native method:

The following code shows the usage of reduce:

<html>
<script>

var a = [1,2,3,4];

function fn(pre, cur, index, arr){
    console.log(`previous: ${pre}, cur: ${cur},
        index: ${index}, whole arr: ${arr}`);
    return pre + cur;
}

console.log(a.reduce( fn, 0));

</script>
</html>

reduce accepts two parameters, the first parameter is a function, the function receives 4 input parameters, previous, current, index and array:

  • previous: The previous round of reduce iteration value, if the first round, this value is the second parameter, which is the initial value
  • current: The current round of reduce iteration value. For example, if the elements of array are 1, 2, 3, 4, then each iteration of reduce, the current value is 1, 2, 3, 4, respectively.
  • index: the index value of the iteration
  • array: The original array of the call to reduce, with the previous index parameter, you can access the contents of the entire array

In actual use, the two parameters, previous and current, are used the most.

Back to the implementation of pipeFromArray.

The first iteration of reduce:

prev is the initial value passed in by input, and fn is the first element of the input fns array. That is, the operator returned by the first map:

The specific map operation is not performed here, but a new Observable object is returned as the input of the second round of reduce iteration:

The lift method is to return a new Observable object:

Implementation of mapTo:

After the Observable processed by the pipe, the final version of the Observable that the application subscribes to is this final version:

More original articles by Jerry, all in: "Wang Zixi":


注销
1k 声望1.6k 粉丝

invalid