utils.ts 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import { IBlock, IExercise, IRating } from './types'
  2. /**
  3. * Takes a block of exercises and calculates the duration in seconds.
  4. * @param block
  5. */
  6. export function calculateDuration(block: IBlock): number {
  7. if (block.duration) return block.duration
  8. const repetitions = block.repetitions || 1
  9. const rest = block.rest || 0
  10. if (block.blocks) {
  11. const subblockDuration = block.blocks.reduce(
  12. (accumulator, block) =>
  13. accumulator + (block.duration || calculateDuration(block)),
  14. 0
  15. )
  16. return repetitions * (subblockDuration + rest)
  17. } else {
  18. return 0
  19. }
  20. }
  21. /**
  22. * Formats a time in seconds into 0:00
  23. * @param seconds
  24. */
  25. export function formatTime(seconds: number) {
  26. return `${Math.floor(seconds / 60)}:${(seconds % 60)
  27. .toString()
  28. .padStart(2, '0')}`
  29. }
  30. /**
  31. * Takes an array of exercises and formats them into
  32. * 4x Exercise 1 - Exercise 2 - 2x Exercise 3
  33. * @param exercises
  34. */
  35. export function printExercises(exercises: IExercise[]) {
  36. return exercises
  37. .map(exercise =>
  38. exercise.repetitions > 1
  39. ? `${exercise.repetitions}x ${exercise.name}`
  40. : exercise.name
  41. )
  42. .join(' - ')
  43. }
  44. /**
  45. * Takes an array of rating and calculates the average rating
  46. * @param ratings
  47. */
  48. export function calculateRating(ratings: IRating[]) {
  49. const numberOfRatings = ratings.length
  50. const sumOfRatings = ratings.reduce(
  51. (accumulator, rating) => accumulator + rating.value,
  52. 0
  53. )
  54. return numberOfRatings ? sumOfRatings / numberOfRatings : '-'
  55. }