All files / src/helpers calculator.ts

94.29% Statements 33/35
80% Branches 8/10
85.71% Functions 6/7
93.55% Lines 29/31

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 761x           1x 1x     1x 1x                   3x 3x 3x     1x                     3x 14x 3x 3x 3x 3x 3x                   1x 3x 3x 3x   1x 1x   1x 1x   1x       1x   3x   1x   1x  
import {
  format,
  differenceInHours,
  differenceInMinutes,
  addHours
} from "date-fns";
import chalk from "chalk";
import Formatter from "../formatter";
import { isNumber } from "util";
 
class Calculator {
  format = new Formatter();
  constructor() {}
 
  /**
   * Calculates the number of hours worked so far from right now.
   *
   * @param startTime The time you started working.
   * @param newTime The time right now to measure against. Defaults to now.
   * @returns the number of hours worked so far.
   */
  hoursWorkedSoFar(startTime: Date, InowTime: Date = new Date()): number {
    const minutesWorked = differenceInMinutes(startTime, nowTime);
    return minutesWorked / 60;
  }
 
  estimateEndTime(hours: number, comparison: number) {
    let difference: number = Number(hours - comparison) * -1;
    return format(addHours(new Date(), difference), "hh:mma");
  }
 
  /**
   * Converts a simple time string to a JavaScript date.
   *
   * @param time A simple time layout.
   * @returns A converted time in the date format.
   */
  convertTimeToDate(time: string, Idate: Date = new Date()): Date {
    const splitTime = time.split("").filter(i => !isNaN(i as any));
    if (splitTime.length === 3) splitTime.unshift("0");
    const hour = Number(`${splitTime[0]}${splitTime[1]}`);
    const minutes = Number(`${splitTime[2]}${splitTime[3]}`);
    date.setHours(hour, minutes);
    return date;
  }
 
  /**
   * Finds the number of hours left against a compared amount.
   *
   * @param hours Number of hours worked
   * @param comparison Number of hours to compare with hours.
   * @returns the difference of the compared time in colored hours.
   */
  difference(hours: number, comparison: number): string {
    let difference: number = Number((hours - comparison).toFixed(2));
    let differenceOut: string = "";
    switch (true) {
      case difference > 0:
        differenceOut = chalk.green(`+${this.format.hours(difference)}`);
        break;
      case difference == 0:
        differenceOut = chalk.yellow(` ${this.format.hours(0)}`);
        break;
      case difference < 0:
        differenceOut = chalk.red(
          `-${this.format.hours(Math.abs(difference))}`
        );
      default:
        difference;
    }
    return differenceOut;
  }
}
 
export default Calculator;