github.com/zignig/go-ipfs@v0.0.0-20141111235910-c9e5fdf55a52/tour/tour.go (about)

     1  package tour
     2  
     3  import (
     4  	"strconv"
     5  	"strings"
     6  
     7  	u "github.com/jbenet/go-ipfs/util"
     8  )
     9  
    10  var log = u.Logger("tour")
    11  
    12  // ID is a string identifier for topics
    13  type ID string
    14  
    15  // LessThan returns whether this ID is sorted earlier than another.
    16  func (i ID) LessThan(o ID) bool {
    17  	return compareDottedInts(string(i), string(o))
    18  }
    19  
    20  // IDSlice implements the sort interface for ID slices.
    21  type IDSlice []ID
    22  
    23  func (a IDSlice) Len() int           { return len(a) }
    24  func (a IDSlice) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
    25  func (a IDSlice) Less(i, j int) bool { return a[i].LessThan(a[j]) }
    26  
    27  // Topic is a type of objects that structures a tour topic.
    28  type Topic struct {
    29  	ID ID
    30  	Content
    31  }
    32  
    33  type Content struct {
    34  	Title string
    35  	Text  string
    36  }
    37  
    38  // Topics is a sorted list of topic IDs
    39  var IDs []ID
    40  
    41  // Topics contains a mapping of Tour Topic ID to Topic
    42  var Topics = map[ID]Topic{}
    43  
    44  // NextTopic returns the next in-order topic
    45  func NextTopic(topic ID) ID {
    46  	for _, id := range IDs {
    47  		if topic.LessThan(id) {
    48  			return id
    49  		}
    50  	}
    51  	return topic // last one, it seems.
    52  }
    53  
    54  // TopicID returns a valid tour topic ID from given string
    55  func TopicID(t string) ID {
    56  	if t == "" { // if empty, use first ID
    57  		return IDs[0]
    58  	}
    59  	return ID(t)
    60  }
    61  
    62  func compareDottedInts(i, o string) bool {
    63  	is := strings.Split(i, ".")
    64  	os := strings.Split(o, ".")
    65  
    66  	for n, vis := range is {
    67  		if n >= len(os) {
    68  			return false // os is smaller.
    69  		}
    70  
    71  		vos := os[n]
    72  		ivis, err1 := strconv.Atoi(vis)
    73  		ivos, err2 := strconv.Atoi(vos)
    74  		if err1 != nil || err2 != nil {
    75  			log.Error(err1)
    76  			log.Error(err2)
    77  			panic("tour ID LessThan: not an int")
    78  		}
    79  
    80  		if ivis < ivos {
    81  			return true
    82  		}
    83  
    84  		if ivis > ivos {
    85  			return false
    86  		}
    87  	}
    88  
    89  	return len(os) > len(is)
    90  }