spreadsheet: fix bug with column to index

This commit is contained in:
Todd 2017-09-15 17:34:12 -05:00
parent 9b89ae1f12
commit 199db803a0
2 changed files with 25 additions and 11 deletions

View File

@ -51,16 +51,18 @@ func ColumnToIndex(col string) uint32 {
// IndexToColumn maps a column number to a coumn name (e.g. 0 = A, 1 = B, 26 = AA)
func IndexToColumn(col uint32) string {
col++
res := []byte{}
for col > 26 {
res = append(res, byte('A'+(col-1)%26))
col /= 26
var a [64 + 1]byte
i := len(a)
u := col
const b = 26
for u >= b {
i--
q := u / b
a[i] = byte('A' + uint(u-q*b))
u = q - 1
}
res = append(res, byte('A'+(col-1)%26))
// reverse it
for i := 0; i < len(res)/2; i++ {
res[i], res[len(res)-i-1] = res[len(res)-i-1], res[i]
}
return string(res)
i--
a[i] = byte('A' + uint(u))
return string(a[i:])
}

View File

@ -57,6 +57,8 @@ func TestColumnToIndex(t *testing.T) {
{"AA", 26},
{"AB", 27},
{"AC", 28},
{"BZ", 77},
{"CA", 78},
{"GOOXML", 90304485},
}
for _, tc := range td {
@ -69,3 +71,13 @@ func TestColumnToIndex(t *testing.T) {
}
}
}
func TestColumnToIndexRoundTrip(t *testing.T) {
for i := 0; i < 10000; i++ {
s := spreadsheet.IndexToColumn(uint32(i))
got := spreadsheet.ColumnToIndex(s)
if got != uint32(i) {
t.Errorf("failed on %d %s", i, s)
}
}
}