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
41 changes: 38 additions & 3 deletions internal/daysteps/daysteps.go
Original file line number Diff line number Diff line change
@@ -1,15 +1,40 @@
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("количество элементов слайса не равно 2")
}
steps, err := strconv.Atoi(res[0])
if err != nil {
return 0, 0, errors.New("невозможно преобразовать элемент слайса в int")
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  1. Теряешь сообщение об ошибки
  2. Ошибку лучше писать на английском
Suggested change
return 0, 0, errors.New("невозможно преобразовать элемент слайса в int")
return 0, 0, fmt.Errorf("conversion error: %w", err)

}
if steps <= 0 {
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Нет проверки на меньше или равно 0

return 0, 0, errors.New("количество шагов меньше или равно 0")
}
duration, err := time.ParseDuration(res[1])
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Нет проверки длительности на меньше или равно 0

if err != nil {
return 0, 0, errors.New("невозможно преобразовать элемент слайса в time.Duration")
}

return steps, duration, nil
}

// DayActionInfo обрабатывает входящий пакет, который передаётся в
Expand All @@ -19,5 +44,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("В функции DayActionInfo произошла оишибка: %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)
}
56 changes: 50 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,20 @@ const (
)

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

res := strings.Split(data, ",")
if len(res) != 3 {
return 0, "", 0, errors.New("количество элементов слайса не равно 3")
}
steps, err := strconv.Atoi(res[0])
if err != nil {
return 0, "", 0, errors.New("невозможно преобразовать элемент слайса в int")
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  1. Теряешь сообщение об ошибки
  2. Ошибку лучше писать на английском
Suggested change
return 0, "", 0, errors.New("невозможно преобразовать элемент слайса в int")
return 0, 0, fmt.Errorf("conversion error: %w", err)

}
duration, err := time.ParseDuration(res[2])
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Нет проверки длительности на меньше или равно 0

if err != nil {
return 0, "", 0, errors.New("невозможно преобразовать элемент слайса в time.Duration")
}
return steps, res[1], duration, nil
}

// distance возвращает дистанцию(в километрах), которую преодолел пользователь за время тренировки.
Expand All @@ -21,7 +38,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 +48,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 +63,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 +100,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 +120,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
}