github.com/aarzilli/tools@v0.0.0-20151123112009-0d27094f75e0/net/http/dedup/5_similar_texts_sort.go (about)

     1  package dedup
     2  
     3  import (
     4  	"fmt"
     5  	"sort"
     6  	"strings"
     7  
     8  	"github.com/pbberlin/tools/util"
     9  )
    10  
    11  type sortByOutline []*TextifiedTree
    12  
    13  func (s sortByOutline) Len() int {
    14  	return len(s)
    15  }
    16  
    17  func (s sortByOutline) Swap(i, j int) {
    18  	s[i], s[j] = s[j], s[i]
    19  }
    20  
    21  func (s sortByOutline) Less(i, j int) bool {
    22  
    23  	var sortByLevelFirst bool = true
    24  
    25  	if sortByLevelFirst {
    26  		lvl1 := strings.Count(s[i].Outline, ".")
    27  		lvl2 := strings.Count(s[j].Outline, ".")
    28  		if lvl1 < lvl2 {
    29  			return true
    30  		}
    31  		if lvl1 > lvl2 {
    32  			return false
    33  		}
    34  	}
    35  
    36  	// A pure number comparison
    37  	// 1.1, 1.2, 2.1, 2.1.1.
    38  	st1 := strings.Split(s[i].Outline, ".")
    39  	st2 := strings.Split(s[j].Outline, ".")
    40  
    41  	for idx, v1 := range st1 {
    42  
    43  		if idx > len(st2)-1 {
    44  			// i.e. 2.37.2 > 2.
    45  			return false
    46  		}
    47  		v2 := st2[idx]
    48  
    49  		if util.Stoi(v1) < util.Stoi(v2) {
    50  			return true
    51  		}
    52  
    53  		if util.Stoi(v1) > util.Stoi(v2) {
    54  			return false
    55  		}
    56  
    57  	}
    58  
    59  	// i.e. 2 < 2.26.1.1
    60  	return true
    61  }
    62  
    63  //
    64  // px prints deebug info for the outline sorting
    65  func px(st1, st2 []string, idx int, op string) {
    66  
    67  	var ps1, ps2 []byte
    68  
    69  	for i := 0; i <= idx; i++ {
    70  		if i > 0 {
    71  			ps1 = append(ps1, '.')
    72  		}
    73  		v1 := "-"
    74  		if i < len(st1)-1 {
    75  			v1 = st1[i]
    76  		}
    77  		ps1 = append(ps1, v1...)
    78  
    79  		//
    80  		if i > 0 {
    81  			ps2 = append(ps2, '.')
    82  		}
    83  		v2 := "-"
    84  		if i < len(st2)-1 {
    85  			v2 = st2[i]
    86  		}
    87  		ps2 = append(ps2, v2...)
    88  
    89  		if v1 == "-" && v2 == "-" {
    90  			break
    91  		}
    92  	}
    93  
    94  	pf("%10v %s %10v    \n", string(ps1), op, string(ps2))
    95  
    96  }
    97  
    98  // apply ordering
    99  func orderByOutline(m []*TextifiedTree) ([]*TextifiedTree, []byte) {
   100  
   101  	// sort.Strings(outlines)
   102  	sort.Sort(sortByOutline(m))
   103  
   104  	buf := []byte{}
   105  
   106  	for _, tt := range m {
   107  		row := fmt.Sprintf("%-12v: %s\n", tt.Outline, tt.Text)
   108  		buf = append(buf, row...)
   109  	}
   110  
   111  	return m, buf
   112  
   113  }