Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 40 additions & 3 deletions internal/daysteps/daysteps.go
Original file line number Diff line number Diff line change
@@ -1,15 +1,42 @@
package daysteps

import (
"errors"
"fmt"
"strconv"
"strings"
"time"

"github.com/Yandex-Practicum/go1fl-4-sprint-final/internal/spentcalories"
)

var (
const (
StepLength = 0.65 // длина шага в метрах
mKm = 1000 // количество метров в километре.
)

func parsePackage(data string) (int, time.Duration, error) {
// ваш код ниже

res := strings.Split(data, ",")

if len(res) != 2 {
return 0, 0, errors.New("slice is not equal 2")
}
steps, err := strconv.Atoi(res[0])
if err != nil {
return 0, 0, fmt.Errorf("conversion error: %w", err)
}
if steps <= 0 {
return 0, 0, errors.New("number of steps less than or equal 0")
}
duration, err := time.ParseDuration(res[1])
if err != nil {
return 0, 0, fmt.Errorf("conversion error: %w", err)
}
if duration <= 0 {
return 0, 0, errors.New("number of duration less than or equal 0")
}
return steps, duration, nil
}

// DayActionInfo обрабатывает входящий пакет, который передаётся в
Expand All @@ -19,5 +46,15 @@ func parsePackage(data string) (int, time.Duration, error) {
// Если пакет валидный, он добавляется в слайс storage, который возвращает
// функция. Если пакет невалидный, storage возвращается без изменений.
func DayActionInfo(data string, weight, height float64) string {
// ваш код ниже
steps, duration, err := parsePackage(data)
if err != nil {
fmt.Printf("error in the DayActionInfo function: %v\n", err)
return ""
}
if steps <= 0 {
return ""
}
distance := (float64(steps) * StepLength) / mKm
calories := spentcalories.WalkingSpentCalories(steps, weight, height, duration)
return fmt.Sprintf("Количество шагов: %d.\nДистанция составила %.2f км.\nВы сожгли %.2f ккал.", steps, distance, calories)
}
62 changes: 56 additions & 6 deletions internal/spentcalories/spentCalories.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
package spentcalories

import (
"errors"
"fmt"
"strconv"
"strings"
"time"
)

Expand All @@ -12,7 +16,26 @@ const (
)

func parseTraining(data string) (int, string, time.Duration, error) {
// ваш код ниже

res := strings.Split(data, ",")
if len(res) != 3 {
return 0, "", 0, errors.New("slice is not equal 3")
}
steps, err := strconv.Atoi(res[0])
if err != nil {
return 0, "", 0, fmt.Errorf("conversion error: %w", err)
}
if steps <= 0 {
return 0, "", 0, errors.New("number of steps less than or equal 0")
}
duration, err := time.ParseDuration(res[2])
if err != nil {
return 0, "", 0, fmt.Errorf("conversion error: %w", err)
}
if duration <= 0 {
return 0, "", 0, errors.New("number of duration less than or equal 0")
}
return steps, res[1], duration, nil
}

// distance возвращает дистанцию(в километрах), которую преодолел пользователь за время тренировки.
Expand All @@ -21,7 +44,7 @@ func parseTraining(data string) (int, string, time.Duration, error) {
//
// steps int — количество совершенных действий (число шагов при ходьбе и беге).
func distance(steps int) float64 {
// ваш код ниже
return (float64(steps) * lenStep) / mInKm
}

// meanSpeed возвращает значение средней скорости движения во время тренировки.
Expand All @@ -31,7 +54,12 @@ func distance(steps int) float64 {
// steps int — количество совершенных действий(число шагов при ходьбе и беге).
// duration time.Duration — длительность тренировки.
func meanSpeed(steps int, duration time.Duration) float64 {
// ваш код ниже
if duration <= 0 {
return 0
}
distance := distance(steps)

return distance / duration.Hours()
}

// ShowTrainingInfo возвращает строку с информацией о тренировке.
Expand All @@ -41,7 +69,27 @@ func meanSpeed(steps int, duration time.Duration) float64 {
// data string - строка с данными.
// weight, height float64 — вес и рост пользователя.
func TrainingInfo(data string, weight, height float64) string {
// ваш код ниже

steps, trainingType, duration, err := parseTraining(data)
if err != nil {
return ""
}
var dist, speed, calories float64
switch trainingType {
case "Ходьба":
dist = distance(steps)
speed = meanSpeed(steps, duration)
calories = WalkingSpentCalories(steps, weight, height, duration)

case "Бег":
dist = distance(steps)
speed = meanSpeed(steps, duration)
calories = RunningSpentCalories(steps, weight, duration)
default:
fmt.Println("неизвестный тип тренировки")
}

return fmt.Sprintf("Тип тренировки: %s\nДлительность: %s ч.\nДистанция: %.2f км.\nСкорость: %.2f\nСожгли калорий: %.2f\n", trainingType, duration, dist, speed, calories)
}

// Константы для расчета калорий, расходуемых при беге.
Expand All @@ -58,8 +106,9 @@ const (
// weight float64 — вес пользователя.
// duration time.Duration — длительность тренировки.
func RunningSpentCalories(steps int, weight float64, duration time.Duration) float64 {
// ваш код здесь

meanSpeed := meanSpeed(steps, duration)
return ((runningCaloriesMeanSpeedMultiplier * meanSpeed) - runningCaloriesMeanSpeedShift) * weight
}

// Константы для расчета калорий, расходуемых при ходьбе.
Expand All @@ -77,6 +126,7 @@ const (
// weight float64 — вес пользователя.
// height float64 — рост пользователя.
func WalkingSpentCalories(steps int, weight, height float64, duration time.Duration) float64 {
// ваш код здесь

meanSpeed := meanSpeed(steps, duration)
return ((walkingCaloriesWeightMultiplier * weight) + (meanSpeed*meanSpeed/height)*walkingSpeedHeightMultiplier) * duration.Hours() * minInH
}