typescript - 如何将 TypeScript 类方法转换为不写入函数内的类状态的纯函数?
问题描述
在进入 TypeScript 和 Angular 面向对象的趋势世界一段时间后,我正努力回到 Node 中的函数式编程,我正试图让我的类方法“纯粹”。据我了解,我无法更改方法中的参数,也无法直接在方法中写入私有类变量。我将如何转换processNewImageStack
为纯函数?(完整的代码在这里)
export class MotionCapturer {
// Stack images ready for upload as able.
private uploadImageStack = new FileStack();
private uploadImageBusy: false;
// ...
/**
* Process the new cam image stack one item at a time as available.
*/
private processNewImageStack = async (): Promise<void> => {
if (this.newImageBusy === false && this.newImageStack.length > 0) {
// Don't process other stack items until this one is finished.
this.newImageBusy = true;
// Take the top/last item in the stack.
const stackImage = this.newImageStack.pop();
try {
// Get the image thumbnail for comparison with previous thumbnail when detecting motion
const thumbPath = await this.extractThumbnailAsFile(stackImage, this.options.tempImageDirectory);
const newThumb = await this.loadThumbnail(thumbPath);
// Detect motion.
const motionDetected = this.detectMotion(newThumb, this.previousThumb, this.motionHotspots, this.options.motionSensitivity);
// Upload image if motion was detected.
if (motionDetected) {
const movedImage = await this.moveFile(stackImage,
this.options.readyImageDirectory);
this.previousThumb = newThumb; // also setting directly hmm
this.uploadImageStack.push(movedImage);
}
} catch (err) {
console.error('processNewImageStack error', err);
}
// All done, open for next item in the stack
this.newImageBusy = false;
}
return;
}
private extractThumbnailAsFile = (imagePath: string, tempImageDir: string): Promise<string> => {
// ...
}
private loadThumbnail = async (thumbImagePath: string): Promise<Jimp> => {
// ...
};
private detectMotion = (newThumb: Jimp, prevThumb: Jimp, hotspots: HotspotBoundingBox[], motionSensitivity: number): boolean => {
// ...
};
private moveFile = (filePath: string, destinationDir: string): Promise<string> => {
// ...
}
public init = (): void => {
setInterval(() => this.processNewImageStack, 500);
}
}
目前它正在检查this.newImageBusy
and this.newImageStack.length
,我猜我应该将其设置为参数?此外,它的设置this.newImageBusy
超出了该方法的范围。我应该调用一个设置它而不是设置的函数,对吗?
另外,我知道类似乎在函数式编程之外。我可以单独解决这个问题。
解决方案
推荐阅读
- sql-server - SSRS Parameters多值问题(全选不起作用)
- javascript - 如何编辑 Material UI Card 的内容
- javascript - 在不相关的组件之间反应上下文
- dom - 是否有使用当前仅在页面加载时读取源代码(+highlights 关键字)的 Chrome 扩展程序突出显示后续 DOM 更改的修复程序?
- python - 如何将 pandas.core.frame.DataFrame 转换为列表?
- docker-compose - 与 docker bind 和 type 参数混淆
- java - 从 S3 存储桶中获取所有对象的最佳方法是什么
- python - 我已经尝试了所有方法,但我的 pack_forget 在 tkinter 中不起作用?
- c# - 在 Unity 中使用 HTTP Put json
- mysql - 在 SQL 查询中使用 count 时未处理 MySqlException