aboutsummaryrefslogtreecommitdiff
path: root/src/step.ts
blob: 13ca18377b5d91d15f6bc6307df6bc4b0f0fb3a9 (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
64
65
66
67
68
69
70
71
72
73
74
import * as Config from 'config'

export type Step
  = { name: 'warmup', remaining: number }
  | { name: 'prepare', tabata: string, remaining: number }
  | { name: 'work', tabata: string, cycle: number, remaining: number }
  | { name: 'rest', tabata: string, cycle: number, remaining: number }
  | { name: 'end' }

export function prettyPrint(step: Step): string {
  switch (step.name) {
    case 'warmup':
      return 'Warm Up'
    case 'prepare':
      return `${step.tabata}\nPreparation`
    case 'work':
      return `${step.tabata}\nWork ${step.cycle}`
    case 'rest':
      return `${step.tabata}\nRest ${step.cycle}`
    case 'end':
      return 'End!'
  }
}

export function getAt(config: Config.Config, elapsed: number): Step {
  if (elapsed < config.warmup) {
    return {
      name: 'warmup',
      remaining: config.warmup - elapsed
    }
  }

  const tabataElapsed = elapsed - config.warmup

  const cycleDuration = config.work + config.rest
  const tabataDuration = config.prepare + (config.cycles * cycleDuration)

  if (tabataElapsed >= tabataDuration * config.tabatas.length) {
    return { name: 'end' }
  }

  const tabata = config.tabatas[Math.floor(tabataElapsed / tabataDuration)]
  const currentTabataElapsed = tabataElapsed % tabataDuration

  if (currentTabataElapsed < config.prepare) {
    return {
      name: 'prepare',
      tabata,
      remaining: config.prepare - currentTabataElapsed
    }
  } else {
    const currentCycleElapsed = (currentTabataElapsed - config.prepare) % cycleDuration
    const cycle =
      currentTabataElapsed < config.prepare
        ? 1
        : Math.floor((currentTabataElapsed - config.prepare) / cycleDuration) + 1

    if (currentCycleElapsed < config.work) {
      return {
        name: 'work',
        tabata,
        cycle,
        remaining: config.work - currentCycleElapsed
      }
    } else {
      return {
        name: 'rest',
        tabata,
        cycle,
        remaining: config.work + config.rest - currentCycleElapsed
      }
    }
  }
}