Anonymous (owner)

Revisions

  • a2c1b8 Tue Jan 13 10:55:43 -0800 2009
gist: 46562 Download_button fork
public
Description:
sparkword command for ubiquity, see http://blog.jonudell.net/2009/01/13/fuel-prices-and-pageviews
Public Clone URL: git://gist.github.com/46562.git
Embed All Files: show embed
x #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
CmdUtils.CreateCommand({
  name: "sparkword",
  description: "Graphs the current selection, turning it into a textual sparkline.",
  takes: {"data": noun_arb_text},
  // really this is Aza Raskin's code with a small change from me
  author: {name: "Brian Ewins", email:"brian.ewins@gmail.com"},
  license: "MIT",
  help: "Select a set of numbers -- in a table or otherwise -- and use this command to graph them as a sparkline. Don't worry about non-numbers getting in there. It'll handle them.",
 
  _cleanData: function( string ) {
    var dirtyData = string.split(/\W/);
    var data = [];
    for(var i=0; i<dirtyData.length; i++){
      var datum = parseFloat( dirtyData[i] );
      if( datum.toString() != "NaN" ){
        data.push( datum );
      }
    }
 
    return data;
  },
 
  _dataToSparkline: function( string ) {
    var data = this._cleanData( string );
    if( data.length < 2 ) return null;
 
    var data = this._cleanData( string );
    if( data.length < 2 ) return null;
    var min = 9999;
    var max = -1;
 
    for ( var i = 0; i < data.length; i++ ) {
       data[i] = data[i] - 0;
       if ( data[i] < min ) min = data[i];
       if ( data[i] > max ) max = data[i];
    }
 
    // Use 1/8 as baseline
    var chars="\u2581\u2582\u2583\u2584\u2585\u2586\u2587\u2588";
    var scale = (max == min) ? 1 : 7./(max - min);
    var sparkword = "";
    for (var i = 0; i < data.length; i++) {
      var h = Math.round((data[i] - min) * scale);
      sparkword += chars.charAt(h);
    }
 
    return sparkword;
  },
 
  preview: function(pblock, input) {
    var img = this._dataToSparkline( input.text );
    if( !img )
      jQuery(pblock).text( "Requires numbers to graph." );
    else
      jQuery(pblock).empty().append( img ).height( "15px" );
  },
 
  execute: function( input ) {
    var img = this._dataToSparkline( input.text );
    if( img ) CmdUtils.setSelection( img );
  }
});