Browse Source

Faster TitleToNumber (#343)

* TestTitleToNumber: more test cases

* TitleToNumber: drop use of math.Pow()

Compute using pure integers

* TitleToNumber: simplify

Remove unecessary casts to int
Olivier Mengué 6 năm trước cách đây
mục cha
commit
e780e41e02
2 tập tin đã thay đổi với 10 bổ sung7 xóa
  1. 4 0
      excelize_test.go
  2. 6 7
      lib.go

+ 4 - 0
excelize_test.go

@@ -1546,8 +1546,12 @@ func TestConditionalFormatError(t *testing.T) {
 }
 
 func TestTitleToNumber(t *testing.T) {
+	assert.Equal(t, 0, TitleToNumber("A"))
+	assert.Equal(t, 25, TitleToNumber("Z"))
+	assert.Equal(t, 26, TitleToNumber("AA"))
 	assert.Equal(t, 36, TitleToNumber("AK"))
 	assert.Equal(t, 36, TitleToNumber("ak"))
+	assert.Equal(t, 51, TitleToNumber("AZ"))
 }
 
 func TestSharedStrings(t *testing.T) {

+ 6 - 7
lib.go

@@ -14,7 +14,6 @@ import (
 	"bytes"
 	"io"
 	"log"
-	"math"
 	"strconv"
 	"strings"
 	"unicode"
@@ -91,15 +90,15 @@ func ToAlphaString(value int) string {
 //    excelize.TitleToNumber("ak")
 //
 func TitleToNumber(s string) int {
-	weight := 0.0
+	weight := 1
 	sum := 0
 	for i := len(s) - 1; i >= 0; i-- {
-		ch := int(s[i])
-		if int(s[i]) >= int('a') && int(s[i]) <= int('z') {
-			ch = int(s[i]) - 32
+		ch := s[i]
+		if ch >= 'a' && ch <= 'z' {
+			ch -= 32
 		}
-		sum = sum + (ch-int('A')+1)*int(math.Pow(26, weight))
-		weight++
+		sum += int(ch-'A'+1) * weight
+		weight *= 26
 	}
 	return sum - 1
 }