Skip to content

Instantly share code, notes, and snippets.

/x

Created January 13, 2009 18:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/46562 to your computer and use it in GitHub Desktop.
Save anonymous/46562 to your computer and use it in GitHub Desktop.
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 );
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment