JS数据压缩算法3+

13,891 views / 2009.09.04 / 12:12 下午

研究Google chart API的时候发现它提供的数据压缩算法不错,可以把纯数字的数组压缩成很短的一个字符串,分享如下:

var simpleEncoding = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
 
function simpleEncode(values,maxValue) {
 
var chartData = ['s:'];
for (var i = 0; i < values.length; i++) { var currentValue = values[i]; if (!isNaN(currentValue) && currentValue >= 0) {
chartData.push(simpleEncoding.charAt(Math.round((simpleEncoding.length-1) * currentValue / maxValue)));
} else {
chartData.push('_');
}
}
return chartData.join('');
}

测试例子:

var valueArray = new Array(20,100,40,50,60,81,74);
var maxValue = 100;
document.write(simpleEncode(valueArray,maxValue));
Categories: 分享 Tags: , , ,