Как преобразовать метод класса TypeScript в чистую функцию, которая не записывает в состояние класса внутри функции? - PullRequest
0 голосов
/ 07 апреля 2020

Возвращаясь к функциональному программированию в Node, после того, как некоторое время попадаю в мир объектно-ориентированных тенденций TypeScript и * 1013, я пытаюсь сделать свои методы класса «чистыми». Из того, что я понимаю, я не могу изменить параметр в методе и не могу записать в переменную частного класса непосредственно в методе. Как бы я преобразовал 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 и this.newImageStack.length, что, я полагаю, следует установить в качестве параметров? Кроме того, он устанавливает this.newImageBusy вне области действия метода. Мне следует вызвать функцию, которая устанавливает ее вместо установки, правильно?

Кроме того, я знаю, что классы находятся за пределами функционального программирования. Я могу обратиться к этому отдельно.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...