Posted to tcl by dbohdan at Thu Sep 12 17:06:53 GMT 2019view raw
- #! /usr/bin/env tclsh
- # https://wiki.tcl-lang.org/page/Sparkline, one-$ version
- proc $ var-name {
- upvar 1 ${var-name} var
- return $var
- }
- namespace eval sparklines {
- namespace export create
- variable version 0.0.5
- variable ticks [list ]
- variable tick-max [expr {
- [llength [$ ticks]] - 1
- }]
- proc create data {
- variable ticks
- variable tick-max
- set sorted [lsort -real [$ data]]
- set min [lindex [$ sorted] 0]
- set max [lindex [$ sorted] end]
- if {[$ min] == [$ max]} {
- # All data points are the same.
- return [string repeat \
- [lindex [$ ticks] [expr {int([$ tick-max] / 2)}]] \
- [llength [$ data]]]
- } else {
- set result {}
- foreach x [$ data] {
- set x-normalized [expr {
- int([$ tick-max] * ([$ x] - [$ min]) /
- ([$ max] - [$ min]))
- }]
- append result [lindex [$ ticks] [$ x-normalized]]
- }
- return [$ result]
- }
- }
- }
- # The following code allows you to use this script from the command line much
- # like the Bash version mentioned above.
- proc main-script? {} {
- # From https://wiki.tcl-lang.org/40097.
- global argv0
- if {[info exists argv0]
- && [file exists [info script]]
- && [file exists [$ argv0]]} {
- file stat [$ argv0] argv0-info-arr
- file stat [info script] script-info-arr
- set argv0-info [array get argv0-info-arr]
- set script-info [array get script-info-arr]
- expr {
- [dict get [$ argv0-info] dev] == [dict get [$ script-info] dev]
- && [dict get [$ argv0-info] ino] == [dict get [$ script-info] ino]
- }
- } else {
- return 0
- }
- }
- if {[main-script?]} {
- if {[$ argv] eq ""} {
- puts "usage: [$ argv0] value ?value...?"
- puts " [$ argv0] \"value ?value...?\""
- } elseif {[$ argv] eq "test"} {
- proc assert {v1 v2} {
- if {[$ v1] eq [$ v2]} {
- puts [$ v1]
- } else {
- error "assertion failed: \"[$ v1]\" ne \"[$ v2]\""
- }
- }
- assert [sparklines::create {1 5 22 13 53}] {}
- assert [sparklines::create {0 30 55 80 33 150}] {}
- assert [sparklines::create {9 13 5 17 1}] {}
- assert [sparklines::create {1 1 1 1}] {}
- puts ok
- } else {
- if {[llength [$ argv]] == 1} {
- set argv [lindex [$ argv] 0]
- }
- puts [sparklines::create [$ argv]]
- }
- }
Comments
Posted by avl at Tue Sep 17 07:09:39 GMT 2019 [text] [code]
interp alias {} $ {} set