Skip to content

Instantly share code, notes, and snippets.

@aaronmccall
Created November 12, 2011 02:39
Show Gist options
  • Save aaronmccall/1359942 to your computer and use it in GitHub Desktop.
Save aaronmccall/1359942 to your computer and use it in GitHub Desktop.
One approach to reducing data over the wire...
<!DOCTYPE html>
<html>
<head>
<title>Zippy Test</title>
<script type="text/javascript" src="zippy.js"></script>
<script type="text/javascript">
console.profile();
var kv_str = 'foo,bar,baz|1,2,3,4,5,6,7,8,9',
zippy_list = string_to_zippy(kv_str, true),
zippy_json = JSON.stringify(zippy_list);
console.group('"%s" is %s bytes', kv_str, kv_str.length);
console.log('final list of dicts: %o', zippy_list);
console.log('"%s" is %s bytes', zippy_json, zippy_json.length);
console.groupEnd();
console.profileEnd();
</script>
</head>
<body></body>
</html>
/**
* @param {Array} keys
* @param {Array} vals
* @param {Boolean} convert_numbers
*/
function zippy(keys, vals, convert_numbers) {
var i = 0, l = keys.length, o, obj, list = [];
while (o = vals.slice(i,i+l)) {
if (!o.length) break;
obj = {};
o.forEach(function(val, index){
if (!convert_numbers) {
obj[keys[index]] = val;
} else if (val.replace(/[^\d]+/g, '') === val) {
obj[keys[index]] = parseInt(val);
} else if (val.replace(/[^\d\.]+/g, '') === val) {
obj[keys[index]] = parseFloat(val);
} else {
obj[keys[index]] = val;
}
});
list.push(obj);
i += l;
}
return list;
}
function string_to_zippy(str, convert_numbers, kvsep, isep) {
var key_value_separator = kvsep||'|',
inner_separator = isep||',',
kv_separated = str.split(key_value_separator),
keys = kv_separated.shift().split(inner_separator),
values = kv_separated.pop().split(inner_separator);
return zippy(keys, values, convert_numbers);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment