github.com/kotovmak/go-admin@v1.1.1/modules/collection/collection.go (about)

     1  package collection
     2  
     3  type Collection []map[string]interface{}
     4  
     5  // Where filters the collection by a given key / value pair.
     6  func (c Collection) Where(key string, values ...interface{}) Collection {
     7  	var d = make([]map[string]interface{}, 0)
     8  	if len(values) < 1 {
     9  		for _, value := range c {
    10  			if isTrue(value[key]) {
    11  				d = append(d, value)
    12  			}
    13  		}
    14  	} else if len(values) < 2 {
    15  		for _, value := range c {
    16  			if value[key] == values[0] {
    17  				d = append(d, value)
    18  			}
    19  		}
    20  	} else if values[0].(string) == "=" {
    21  		for _, value := range c {
    22  			if value[key] == values[1] {
    23  				d = append(d, value)
    24  			}
    25  		}
    26  	}
    27  	return d
    28  }
    29  
    30  func (c Collection) Length() int {
    31  	return len(c)
    32  }
    33  
    34  func (c Collection) FirstGet(key string) interface{} {
    35  	return c[0][key]
    36  }
    37  
    38  func isTrue(a interface{}) bool {
    39  	switch a := a.(type) {
    40  	case uint:
    41  		return a != uint(0)
    42  	case uint8:
    43  		return a != uint8(0)
    44  	case uint16:
    45  		return a != uint16(0)
    46  	case uint32:
    47  		return a != uint32(0)
    48  	case uint64:
    49  		return a != uint64(0)
    50  	case int:
    51  		return a != int(0)
    52  	case int8:
    53  		return a != int8(0)
    54  	case int16:
    55  		return a != int16(0)
    56  	case int32:
    57  		return a != int32(0)
    58  	case int64:
    59  		return a != int64(0)
    60  	case float32:
    61  		return a != float32(0)
    62  	case float64:
    63  		return a != float64(0)
    64  	case string:
    65  		return a != ""
    66  	case bool:
    67  		return a
    68  	default:
    69  		return false
    70  	}
    71  }