diff --git a/internal/daysteps/daysteps.go b/internal/daysteps/daysteps.go index 18bb45c..c4d5c68 100644 --- a/internal/daysteps/daysteps.go +++ b/internal/daysteps/daysteps.go @@ -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 обрабатывает входящий пакет, который передаётся в @@ -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) } diff --git a/internal/spentcalories/spentCalories.go b/internal/spentcalories/spentCalories.go index ed2603a..8b7a4d4 100644 --- a/internal/spentcalories/spentCalories.go +++ b/internal/spentcalories/spentCalories.go @@ -1,6 +1,10 @@ package spentcalories import ( + "errors" + "fmt" + "strconv" + "strings" "time" ) @@ -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 возвращает дистанцию(в километрах), которую преодолел пользователь за время тренировки. @@ -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 возвращает значение средней скорости движения во время тренировки. @@ -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 возвращает строку с информацией о тренировке. @@ -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) } // Константы для расчета калорий, расходуемых при беге. @@ -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 } // Константы для расчета калорий, расходуемых при ходьбе. @@ -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 }