首页 > 解决方案 > 如何将 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.newImageBusyand this.newImageStack.length,我猜我应该将其设置为参数?此外,它的设置this.newImageBusy超出了该方法的范围。我应该调用一个设置它而不是设置的函数,对吗?

另外,我知道类似乎在函数式编程之外。我可以单独解决这个问题。

标签: typescriptfunctional-programming

解决方案


推荐阅读