aboutsummaryrefslogtreecommitdiff
path: root/src/state.ts
blob: 3b390c59d3ca06e0d081fe854336b47c4b7b3498 (plain)
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
import * as Config from 'config'

export enum Step {
  Prepare,
  Work,
  Rest,
  End,
}

export function prettyPrintStep(step: Step): string {
  if (step === Step.Prepare)
    return "Prepare"
  else if (step === Step.Work)
    return "Work"
  else if (step === Step.Rest)
    return "Rest"
  else
    return "End"
}

export interface State {
  step: Step,
  remaining: number,
  tabata: number,
  cycle: number,
}

export function getAt(config: Config.Config, elapsed: number): State {
  const cycleDuration = config.work + config.rest
  const tabataDuration = config.prepare + (config.cycles * cycleDuration)
  if (elapsed >= tabataDuration * config.tabatas) {
    return {
      step: Step.End,
      remaining: 0,
      tabata: config.tabatas,
      cycle: config.cycles,
    }
  } else {
    const currentTabataElapsed = elapsed % tabataDuration
    let step, remaining
    if (currentTabataElapsed < config.prepare) {
      step = Step.Prepare
      remaining = config.prepare - currentTabataElapsed
    } else {
      const currentCycleElapsed = (currentTabataElapsed - config.prepare) % cycleDuration
      if (currentCycleElapsed < config.work) {
        step = Step.Work
        remaining = config.work - currentCycleElapsed
      } else {
        step = Step.Rest
        remaining = config.work + config.rest - currentCycleElapsed
      }
    }

    const tabata = Math.floor(elapsed / tabataDuration) + 1
    const cycle =
      currentTabataElapsed < config.prepare
        ? 1
        : Math.floor((currentTabataElapsed - config.prepare) / cycleDuration) + 1

    return { step, remaining, tabata, cycle }
  }
}