github.com/zlyuancn/zstr@v0.0.0-20230412074414-14d6b645962f/counter.go (about)

     1  /*
     2  -------------------------------------------------
     3     Author :       Zhang Fan
     4     date:         2020/11/25
     5     Description :
     6  -------------------------------------------------
     7  */
     8  
     9  package zstr
    10  
    11  // 计数器, 注意: 非并发安全
    12  type counter struct {
    13  	data map[string]int
    14  	def  int // 默认值
    15  }
    16  
    17  // 创建一个计数器, 非线程安全
    18  func newCounter(initValue ...int) *counter {
    19  	c := &counter{
    20  		data: make(map[string]int),
    21  	}
    22  	if len(initValue) > 0 {
    23  		c.def = initValue[0]
    24  	}
    25  	return c
    26  }
    27  
    28  func (c *counter) Incr(key string) int {
    29  	return c.IncrBy(key, 1)
    30  }
    31  
    32  func (c *counter) IncrBy(key string, num int) int {
    33  	v, ok := c.data[key]
    34  	if !ok {
    35  		v = c.def
    36  	}
    37  	v += num
    38  	c.data[key] = v
    39  	return v
    40  }
    41  
    42  func (c *counter) Get(key string) int {
    43  	v, ok := c.data[key]
    44  	if ok {
    45  		return v
    46  	}
    47  	return c.def
    48  }