TypeScript / React扫描运算符如何在currentvalue = function interface工作?(TypeScript/React how does scan operat

编程入门 行业动态 更新时间:2024-10-17 07:38:16
TypeScript / React扫描运算符如何在currentvalue = function interface工作?(TypeScript/React how does scan operator work where currentvalue = function interface?)

我有一个带有以下参数的扫描运算符:

.scan(function (acc:Message[], x: (msg: Message[]) => Message[]){ return x(acc); }, initialMessages)

我的问题是什么return x(acc)实际返回? 累加器function在这种特殊情况下如何工作? 我对TypeScript和lambda表达式相当陌生,因此非常感谢任何帮助。

I have a scan operator with the following arguments:

.scan(function (acc:Message[], x: (msg: Message[]) => Message[]){ return x(acc); }, initialMessages)

my question is what return x(acc) returns actually? how does the accumulator function work in this particular case? I am quite new to TypeScript and lambda expressions, so any help is much appreciated.

最满意答案

在这种情况下, x(acc)的类型将是Message[] 。 你可以通过第二个参数x的签名来告诉它,它返回Message[] 。

通常scan()接受一个带累加器和值的函数(acc, val) => ... 并发出返回的值。 在这种情况下,进入扫描操作符的发射值val是一个闭包。 这有点不寻常,但非常好。 输出的一个例子

[ 1, 2, 3 ] [ 3, 4, 5 ] [ 4, 5, 6 ]

...将会:

import { Observable } from 'rxjs/Rx'; type Message = number; function scanFn(acc: Message[], x: (msg: Message[]) => Message[]): Message[] { return x(acc); } function mapFn(val: Message): (msg: Message[]) => Message[] { return x => x.map((y, i) => val + i); } Observable.from([1, 3, 4]) .map(mapFn) .scan(scanFn, [1, 2, 3]) .subscribe(console.log);

In this case the type of x(acc) would be Message[]. You can tell this from the signature of the 2nd argument x, which returns Message[].

Usually scan() accepts a function (acc, val) => ... with accumulator and value. and emits the returned value. In this case the emitted value val entering the scan operator is a closure. it's a bit unusual, but perfectly fine. An example which outputs

[ 1, 2, 3 ] [ 3, 4, 5 ] [ 4, 5, 6 ]

...would be:

import { Observable } from 'rxjs/Rx'; type Message = number; function scanFn(acc: Message[], x: (msg: Message[]) => Message[]): Message[] { return x(acc); } function mapFn(val: Message): (msg: Message[]) => Message[] { return x => x.map((y, i) => val + i); } Observable.from([1, 3, 4]) .map(mapFn) .scan(scanFn, [1, 2, 3]) .subscribe(console.log);

更多推荐

本文发布于:2023-08-05 23:32:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1440895.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:运算符   如何在   工作   currentvalue   React

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!