Simplify formatFileSize
No need to use a loop with divisions and multiplications when we have logarithms.
This commit is contained in:
parent
9a4a942cc4
commit
f274394f0e
2 changed files with 8 additions and 10 deletions
|
@ -36,8 +36,8 @@ func (f *funcMap) Map() template.FuncMap {
|
||||||
"hasKey": hasKey,
|
"hasKey": hasKey,
|
||||||
"truncate": truncate,
|
"truncate": truncate,
|
||||||
"isEmail": isEmail,
|
"isEmail": isEmail,
|
||||||
"baseURL": config.Opts.BaseURL,
|
"baseURL": config.Opts.BaseURL,
|
||||||
"rootURL": config.Opts.RootURL,
|
"rootURL": config.Opts.RootURL,
|
||||||
"hasOAuth2Provider": func(provider string) bool {
|
"hasOAuth2Provider": func(provider string) bool {
|
||||||
return config.Opts.OAuth2Provider() == provider
|
return config.Opts.OAuth2Provider() == provider
|
||||||
},
|
},
|
||||||
|
@ -71,7 +71,7 @@ func (f *funcMap) Map() template.FuncMap {
|
||||||
"mustBeProxyfied": func(mediaType string) bool {
|
"mustBeProxyfied": func(mediaType string) bool {
|
||||||
return slices.Contains(config.Opts.ProxyMediaTypes(), mediaType)
|
return slices.Contains(config.Opts.ProxyMediaTypes(), mediaType)
|
||||||
},
|
},
|
||||||
"domain": urllib.Domain,
|
"domain": urllib.Domain,
|
||||||
"hasPrefix": strings.HasPrefix,
|
"hasPrefix": strings.HasPrefix,
|
||||||
"contains": strings.Contains,
|
"contains": strings.Contains,
|
||||||
"replace": func(str, old, new string) string {
|
"replace": func(str, old, new string) string {
|
||||||
|
@ -209,11 +209,7 @@ func formatFileSize(b int64) string {
|
||||||
if b < unit {
|
if b < unit {
|
||||||
return fmt.Sprintf("%d B", b)
|
return fmt.Sprintf("%d B", b)
|
||||||
}
|
}
|
||||||
div, exp := int64(unit), 0
|
base := math.Log(float64(b)) / math.Log(unit)
|
||||||
for n := b / unit; n >= unit; n /= unit {
|
number := math.Pow(unit, base-math.Floor(base))
|
||||||
div *= unit
|
return fmt.Sprintf("%.1f %ciB", number, "KMGTPE"[int64(base)-1])
|
||||||
exp++
|
|
||||||
}
|
|
||||||
return fmt.Sprintf("%.1f %ciB",
|
|
||||||
float64(b)/float64(div), "KMGTPE"[exp])
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -156,6 +156,8 @@ func TestFormatFileSize(t *testing.T) {
|
||||||
input int64
|
input int64
|
||||||
expected string
|
expected string
|
||||||
}{
|
}{
|
||||||
|
{0, "0 B"},
|
||||||
|
{1, "1 B"},
|
||||||
{500, "500 B"},
|
{500, "500 B"},
|
||||||
{1024, "1.0 KiB"},
|
{1024, "1.0 KiB"},
|
||||||
{43520, "42.5 KiB"},
|
{43520, "42.5 KiB"},
|
||||||
|
|
Loading…
Reference in a new issue