Могу ли я использовать два цикла for для одной функции или есть лучший способ? - PullRequest
1 голос
/ 31 марта 2019

Я выписываю домашнее задание, которое я, возможно, изобиловал слишком многими структурами. Это имело смысл в то время. Я хочу пройтись по сезонным скидкам (через 2 разных массива - HighPrices и LowPrices) и просто не уверен, что a) установка хороша или нет, b) как добавить цену в менее избыточной манере.

package main

import (
    "fmt"
    "time"
)

func main() {
    fmt.Println(getPrice(2, "bananas"))
}

func getPrice(p float32, f string) float32 {

    type HighPriceItems struct {
        items []string
        price float32
    }
    type LowPriceItems struct {
        items []string
        price float32
    }
    type seasonMatrix struct {
        h HighPriceItems
        l LowPriceItems
    }
    var seasonPrices = func() seasonMatrix {
        var h = HighPriceItems{}
        var l = LowPriceItems{}

        var season = seasonMatrix{}

        switch time.Now().Month() {

        case time.March, time.April, time.May, time.June, time.July:

            h := append(h.items, "apples", "oranges", "pears")
            l := append(l.items, "bananas", "grapes")
            season.h.items = h
            season.h.price = 4
            season.l.items = l
            season.l.price = 2
            return season
        case time.August, time.September, time.October, time.November, time.December, time.January, time.February:

            h := append(h.items, "bananas", "grapes")
            l := append(l.items, "apples", "oranges", "pears")
            season.h.items = h
            season.h.price = 4
            season.l.price = 2
            season.l.items = l
            return season
        }
        return season
    }

    const normalDiscount float32 = .75

    var x = p * normalDiscount
    var specials = seasonPrices()
    var finalPrice float32

    for _, n := range specials.h.items {

        if f == n {
            if specials.h.price > x {
                finalPrice = specials.h.price

            } else {
                finalPrice = x
            }
        }
    }
    for _, n := range specials.l.items {
        if f == n {
            if specials.l.price > x {
                finalPrice = specials.l.price
            } else {
                finalPrice = x
            }
        }
    }
    return finalPrice
}

1 Ответ

4 голосов
/ 31 марта 2019

Нет причин для типов HighPriceItem и LowPriceItem.

Если вы сделаете его единичным PriceItems, вы сможете превратить 2 цикла for в конце в функцию над PriceItems и избавиться от дублированного кода внутри секунды для цикла.

Также в Go var specials = seasonPrices() обычно записывается как specials := seasonPrices()

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...