Skip to content

Commit

Permalink
Update bar function (#589)
Browse files Browse the repository at this point in the history
* fix indexing issue

* [bar] make default output without ansi codes

* [bar] use actual testing framework
  • Loading branch information
maxim-uvarov authored Sep 1, 2023
1 parent d44a198 commit c0c49f9
Showing 1 changed file with 20 additions and 34 deletions.
54 changes: 20 additions & 34 deletions sourced/progress_bar/bar.nu
Original file line number Diff line number Diff line change
@@ -1,30 +1,32 @@
# construct bars based of a given percentage from a given width (5 is default)
# > bar 0.2
# █
# > bar 0.71 --width 10
# ███████
# > bar 0.71
# ███
def 'bar' [
percentage: float
--background (-b): string = 'default'
--foreground (-f): string = 'default'
--progress (-p) # output the result using 'print -n' with '\r' at the end
--progress (-p) # output the result using 'print -n'
--width (-w): int = 5
] {
let blocks = [null "" "" "" "" "" "" "" ""]
let $whole_part = (($blocks | last) * ($percentage * $width // 1))
let $fraction = (
$blocks
$blocks
| get (
($percentage * $width) mod 1
| $in * ($blocks | length)
| math floor
($percentage * $width) mod 1
| $in * ($blocks | length | $in - 1)
| math round
)
)

let $result = (
$"($whole_part)($fraction)"
| fill -c $' ' -w $width
| $"(ansi -e {fg: ($foreground), bg: ($background)})($in)(ansi reset)"
let result = (
$"($whole_part)($fraction)"
| fill -c $' ' -w $width
| if ($foreground == 'default') and ($background == 'default') {} else {
$"(ansi -e {fg: ($foreground), bg: ($background)})($in)(ansi reset)"
}
)

if $progress {
Expand All @@ -34,28 +36,12 @@ def 'bar' [
}
}

def assert_eq [num: int, expected: string, input_1: float, input_2?] {
let actual = (
if ($input_2 == null) {bar $input_1} else {
bar $input_1 --width $input_2
}
)
let span = (metadata $expected).span;
if $actual != $expected {
error make {
msg: "Actual != Expected",
label: {
text: $"expected ($expected) but got ($actual)", start: $span.start, end: $span.end
}
}
} else {
print $"Test ($num) (ansi green)passed(ansi reset) ✓"
}
}
use std assert equal

#[test]
def bar_tests [] {
assert_eq 1 "[49;39m▏ [0m" 0.03
assert_eq 2 "[49;39m▎ [0m" 0.03 10
assert_eq 3 "[49;39m▊[0m" 0.71 1
assert_eq 4 "[49;39m███████ [0m" 0.71 10
}
equal "█▌ " (bar 0.3)
equal "███ " (bar 0.3 --width 10)
equal "" (bar 0.71 --width 1)
equal "███████" (bar 0.71 --width 10)
}

0 comments on commit c0c49f9

Please sign in to comment.