Skip to content

Instantly share code, notes, and snippets.

@potch
Last active May 30, 2016 20:48
Show Gist options
  • Save potch/ee16dfec3266c50d2f93 to your computer and use it in GitHub Desktop.
Save potch/ee16dfec3266c50d2f93 to your computer and use it in GitHub Desktop.

Sparky- tiny unicode sparklines

Try them in a table!

product price trend
widgets 4.37 ⠉⠉⢄⡠⠤⢄⣀⠤
/*
sparky: tiny unicode sparklines
series: array of values
width (optional): number of characters to use (2 dots per character)
*/
function sparky(series, width) {
var len = series.length;
width = width * 2 || Math.floor(len/2) * 2;
var chunk = (len / width);
var scaled = [];
for (var i = 0; i < width; i++) {
var start = Math.round(i*chunk);
var end = Math.min(Math.round(i * chunk + chunk), len);
var c = series.slice(start, end);
var ca = c.reduce((_, v) => _ + v, 0) / c.length;
scaled.push(ca);
}
var min = scaled.reduce((_, v) => Math.min(_, v), Infinity);
var max = scaled.reduce((_, v) => Math.max(_, v), -Infinity);
var range = max - min;
var binned = scaled.map(v => {
return Math.round((v-min) / range * 3);
});
var out = '';
for (i=0; i < binned.length; i+=2) {
var a = (3-binned[i]);
var b = (3-binned[i+1]);
if (a === 3) {
if (b === 3) {
n = 0x28C0;
} else {
n = 0x2840 + (4 << (b+1));
}
} else {
if (b === 3) {
n = 0x2880 + (1<<a);
} else {
n = 0x2800 + (1<<a) + (1<<(b+3));
}
}
out += String.fromCodePoint(n);
}
return out;
}
@FND
Copy link

FND commented Feb 25, 2016

This is pretty neat, thanks!

Would you mind slapping a license on it to allow reuse without exciting the lawyers?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment