Skip to content

Instantly share code, notes, and snippets.

@DeadlySurgeon
Last active July 24, 2023 02:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DeadlySurgeon/4012083474ff4b4ef0fa464417deed9a to your computer and use it in GitHub Desktop.
Save DeadlySurgeon/4012083474ff4b4ef0fa464417deed9a to your computer and use it in GitHub Desktop.
Golang Terminal Percent Bar
package main
import (
"fmt"
"math"
"strings"
"time"
)
var (
csr = []rune{' ', '▏', '▎', '▍', '▌', '▋', '▊', '▉'}
cR = '█'
)
func main() {
fmt.Print("\033[?25l")
defer func() { fmt.Println("\033[?25h") }()
var p float64
for i := 0.0; i <= 1000; i++ {
p = i / 1000
fmt.Printf("\r%.3d%% >%s<\033[K %.03f", int(p*100), cE(p, 20, true), p)
time.Sleep(5 * time.Millisecond)
}
}
func cE(percent float64, size int, color bool) (bar string) {
if color {
bar += "\033[32m\033[41m"
}
pS := float64(size) * percent
pSR := int(math.Floor(pS))
bar += strings.Repeat(string(cR), pSR)
var pFM float64
if pSR != 0 {
pFM = math.Mod(pS, math.Floor(pS))
} else {
pFM = pS
}
if pSR != size {
id := pFM * float64(len(csr)-1)
iR := int(math.Round(id))
bar += string(csr[iR])
}
if (size-pSR)-1 >= 0 {
bar += strings.Repeat(" ", (size-pSR)-1)
}
// RESET Codes
if color {
bar += "\033[0m\033[41m\033[0m"
}
// fmt.Printf("\033[0mpS: %0.2f pSR: %d pFM: %.2f id: %0.2f r: %d %s\n", pS, pSR, pFM, id, iR, bar)
return bar
}
func percent() float64 {
now := time.Now()
currentInterval := uint64(math.Floor(float64(now.Unix()) / 30.0))
// fmt.Println(currentInterval)
nextIntervalTime := time.Unix(int64((currentInterval+1)*30), 0)
timeUntilNextInterval := nextIntervalTime.Sub(now).Milliseconds()
// fmt.Println(timeUntilNextInterval)
// fmt.Printf("%v%%\n", math.Floor((float64(timeUntilNextInterval)/30000.0)*100))
totalIntervalTime := 30000 // Interval duration in milliseconds
remainingPercentage := float64(timeUntilNextInterval) / float64(totalIntervalTime)
return remainingPercentage
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment