我可以在一个函数上使用两个for循环,还是有更好的方法?

时间:2019-03-31 02:36:35

标签: go

我正在写一个作业问题,这个问题可能是我用过多的结构过度设计的。当时很有意义。我想遍历季节性折扣(通过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 个答案:

答案 0 :(得分:4)

没有理由使用HighPriceItemLowPriceItem类型。

如果将其设为单个PriceItems,则可以将最后的2个for循环转换为PriceItems之上的函数,并消除第二个for循环内的重复代码。

在Go var specials = seasonPrices()中也通常写为specials := seasonPrices()