github.com/andrew00x/gomovies@v0.1.0/pkg/catalog/index.go (about)

     1  package catalog
     2  
     3  import (
     4  	"strings"
     5  
     6  	log "github.com/sirupsen/logrus"
     7  
     8  	"github.com/andrew00x/gomovies/pkg/config"
     9  )
    10  
    11  type Index interface {
    12  	Add(tag string, id int)
    13  	Find(tag string) []int
    14  }
    15  
    16  type IndexFactory func(*config.Config) (Index, error)
    17  
    18  type void struct{}
    19  
    20  var emptyValue void
    21  
    22  func CreateIndex(conf *config.Config) (Index, error) {
    23  	return indexFactory(conf)
    24  }
    25  
    26  var indexFactory IndexFactory
    27  
    28  func init() {
    29  	indexFactory = func(_ *config.Config) (Index, error) {
    30  		return &SimpleIndex{make(map[string]map[int]void)}, nil
    31  	}
    32  }
    33  
    34  type SimpleIndex struct {
    35  	idx map[string]map[int]void
    36  }
    37  
    38  func (i *SimpleIndex) Add(tag string, id int) {
    39  	lower := strings.ToLower(tag)
    40  	if _, ok := i.idx[lower]; !ok {
    41  		i.idx[lower] = make(map[int]void)
    42  	}
    43  	if _, ok := i.idx[lower][id]; !ok {
    44  		i.idx[lower][id] = emptyValue
    45  		log.WithFields(log.Fields{"tag": tag, "id": id}).Debug("Add tag to index")
    46  	}
    47  }
    48  
    49  func (i *SimpleIndex) Find(tag string) []int {
    50  	lower := strings.ToLower(tag)
    51  	result := map[int]void{}
    52  	for key, ids := range i.idx {
    53  		if strings.Contains(key, lower) {
    54  			for id := range ids {
    55  				if _, ok := result[id]; !ok {
    56  					result[id] = emptyValue
    57  				}
    58  			}
    59  		}
    60  	}
    61  	keys := make([]int, 0, len(result))
    62  	for id := range result {
    63  		keys = append(keys, id)
    64  	}
    65  	return keys
    66  }