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
18 changes: 15 additions & 3 deletions internal/actioninfo/actioninfo.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,23 @@
package actioninfo

import (
...
"fmt"
)

// создайте интерфейс DataParser
...
type DataParser interface {
Parse(datastring string) (err error)
ActionInfo() (string, error)
}

// создайте функцию Info()
...
func Info(dataset []string, dp DataParser) {
for _, data := range dataset {
err := dp.Parse(data)
if err != nil {
fmt.Println("Ошибка парсинга:", err)
continue
}
fmt.Println(dp.ActionInfo())
}
}
47 changes: 42 additions & 5 deletions internal/daysteps/daysteps.go
Original file line number Diff line number Diff line change
@@ -1,19 +1,56 @@
package daysteps

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

"github.com/Yandex-Practicum/go1fl-sprint5-final/internal/personaldata"
"github.com/Yandex-Practicum/go1fl-sprint5-final/internal/spentenergy"
)

const (
StepLength = 0.65
)

// создайте структуру DaySteps
...

type DaySteps struct {
Steps int
Duration time.Duration
personaldata.Personal
}

// создайте метод Parse()
...
func (ds *DaySteps) Parse(datastring string) (err error) {
parts := strings.Split(datastring, ",")
if len(parts) == 2 {
Copy link

Choose a reason for hiding this comment

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

Большой блок IF и маленький else - плохо!
Можно просто инвертировать условие, чтобы был маленький IF с выходом из функции
image

num, err := strconv.Atoi(parts[0])
if err != nil {
return errors.New("ошибка конвертации строки в int")
Copy link

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 errors.New("ошибка конвертации строки в int")
return fmt.Errorf("conversion error: %w", err)

}
ds.Steps = num
dur, err := time.ParseDuration(parts[1])
if err != nil {
return errors.New("ошибка конвертации строки в time.Time")
}
ds.Duration = dur
return nil
} else {
return errors.New("длина parts не равна 2")
}
}

// создайте метод ActionInfo()
...
func (ds DaySteps) ActionInfo() (string, error) {
if ds.Duration <= 0 {
Copy link

Choose a reason for hiding this comment

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

Тут нигде не используется в расчетах, так что можно опустить

return "", errors.New("продолжительность прогулки должна быть больше 0")
}
dist := spentenergy.Distance(ds.Steps)
cal, err := spentenergy.WalkingSpentCalories(ds.Steps, ds.Weight, ds.Height, ds.Duration)
if err != nil {
return "", errors.New("ошибка подсчета каллорий")
Copy link

Choose a reason for hiding this comment

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

Suggested change
return "", errors.New("ошибка подсчета каллорий")
return "", fmt.Errorf("error in WalkingSpentCalories: %w", err)

}
return fmt.Sprintf("Количество шагов: %d.\nДистанция составила %.2f км.\nВы сожгли %.2f ккал.", ds.Steps, dist, cal), nil
}
13 changes: 9 additions & 4 deletions internal/personaldata/personaldata.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
package personaldata

import ...
import "fmt"

// Ниже создайте структуру Personal
...
type Personal struct {
Name string
Weight float64
Height float64
}

// Ниже создайте метод Print()
...

func (personal Personal) Print() {
fmt.Printf("Имя: %s\nВес: %.2f\nРост: %.2f\n", personal.Name, personal.Weight, personal.Height)
}
47 changes: 35 additions & 12 deletions internal/spentenergy/spentenergy.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package spentenergy

import ...
import (
"errors"
"time"
)

// Основные константы, необходимые для расчетов.
const (
Expand Down Expand Up @@ -28,8 +31,16 @@ const (
// duration time.Duration — длительность тренировки.
//
// Создайте функцию ниже.
...

func WalkingSpentCalories(steps int, weight, height float64, duration time.Duration) (float64, error) {
if weight < 0 || height < 0 {
return 0, errors.New("вес и рост не может быть меньше 0")
}
if duration < 0 {
return 0, errors.New("продолжительность не должна быть меньше 0")
}
meanSpeed := MeanSpeed(steps, duration)
return ((walkingCaloriesWeightMultiplier * weight) + (meanSpeed*meanSpeed/height)*walkingSpeedHeightMultiplier) * duration.Hours() * minInH, nil
}

// Константы для расчета калорий, расходуемых при беге.
const (
Expand All @@ -46,28 +57,40 @@ const (
// duration time.Duration — длительность тренировки.
//
// Создайте функцию ниже.
...

func RunningSpentCalories(steps int, weight float64, duration time.Duration) (float64, error) {
if weight < 0 {
return 0, errors.New("вес не может быть меньше 0")
}
if duration < 0 {
return 0, errors.New("продолжительность должна быть больше 0")
}
meanSpeed := MeanSpeed(steps, duration)
return ((runningCaloriesMeanSpeedMultiplier * meanSpeed) - runningCaloriesMeanSpeedShift) * weight, nil
}

// МeanSpeed возвращает значение средней скорости движения во время тренировки.
//
// Параметры:
//
// steps int — количество совершенных действий(число шагов при ходьбе и беге).
// duration time.Duration — длительность тренировки.
//
//
// Создайте функцию ниже.
...

func MeanSpeed(steps int, duration time.Duration) float64 {
if duration < 0 {
return 0
}
return Distance(steps) / duration.Hours()
}

// Distance возвращает дистанцию(в километрах), которую преодолел пользователь за время тренировки.
//
// Для расчета дистанции нужно шаги умножить на длину шага lenStep и разделить на mInKm
// Параметры:
//
// steps int — количество совершенных действий (число шагов при ходьбе и беге).
//
//
// Создайте функцию ниже
...


func Distance(steps int) float64 {
return (float64(steps) * lenStep) / mInKm
}
71 changes: 66 additions & 5 deletions internal/trainings/trainings.go
Original file line number Diff line number Diff line change
@@ -1,16 +1,77 @@
package trainings

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

"github.com/Yandex-Practicum/go1fl-sprint5-final/internal/personaldata"
"github.com/Yandex-Practicum/go1fl-sprint5-final/internal/spentenergy"
)

// создайте структуру Training
...

type Training struct {
Steps int
TrainingType string
Duration time.Duration
personaldata.Personal
}

// создайте метод Parse()
...
func (t *Training) Parse(datastring string) (err error) {
var num int
var dur time.Duration
var act string
slice := strings.Split(datastring, ",")
if len(slice) == 3 {
Copy link

Choose a reason for hiding this comment

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

Аналогично нужно инвертировать условие

num, err = strconv.Atoi(slice[0])
if err != nil {
return errors.New("Ошибка конвертации строки в int")
}
t.Steps = num

act = slice[1]
if act != "Бег" || act != "Ходьба" {
return errors.New("неизвестный тип тренировки")
}
t.TrainingType = act
dur, err = time.ParseDuration(slice[2])
if err != nil {
return errors.New("Ошибка конвертации строки в time.Time")
}
t.Duration = dur
} else {
return errors.New("Длина slice не равна 3")
}
return nil

}

// создайте метод ActionInfo()
...
func (t Training) ActionInfo() (string, error) {
distance := spentenergy.Distance(t.Steps)
if t.Duration <= 0 {
return "", fmt.Errorf("длительность тренировки должна быть больше 0")
}
meanSpeed := spentenergy.MeanSpeed(t.Steps, t.Duration)
if t.TrainingType == "Бег" {
cal, err := spentenergy.RunningSpentCalories(t.Steps, t.Weight, t.Duration)
if err != nil {
return "", err
}
return fmt.Sprintf("Тип тренировки: %s\nДлительность: %.2f ч.\nДистанция: %.2f км.\nСкорость: %.2f км/ч\nСожгли калорий: %.2f", t.TrainingType, t.Duration, distance, meanSpeed, cal), nil

} else if t.TrainingType == "Ходьба" {
cal, err := spentenergy.WalkingSpentCalories(t.Steps, t.Weight, t.Height, t.Duration)
if err != nil {
return "", err
}
return fmt.Sprintf("Тип тренировки: %s\nДлительность: %.2f ч.\nДистанция: %.2f км.\nСкорость: %.2f км/ч\nСожгли калорий: %.2f", t.TrainingType, t.Duration, distance, meanSpeed, cal), nil

} else {
return "неизвестный тип тренировки", errors.New("unknown training type")
}

}