Skip to content

Instantly share code, notes, and snippets.

@shawndumas
Created June 28, 2012 15:16
Show Gist options
  • Save shawndumas/3011951 to your computer and use it in GitHub Desktop.
Save shawndumas/3011951 to your computer and use it in GitHub Desktop.
Delimited string decoder / encoder
// [
// { 'id': '123', 'amt': '300', 'price': '3' },
// { 'id': '124', 'amt': '400', 'price': '4' },
// { 'id': '125', 'amt': '500', 'price': '5' }
// ].joseify();
//
// ==> '123|300|3[124|400|4[125|500|5'
Array.prototype.joseify = function (fieldSep, rowSep) {
fieldSep = fieldSep || '|';
rowSep = rowSep || '[';
return this.map(function (value) {
var r = [];
for (var i in value) if (value.hasOwnProperty(i)) {
r.push(value[i]);
}
return r.join(fieldSep);
}).join(rowSep);
};
// '123|300|3[124|400|4[125|500|5'.dejoseify({ '0': 'id', '1': 'amt', '2': 'price' });
//
// ==> [
// { 'id': '123', 'amt': '300', 'price': '3' },
// { 'id': '124', 'amt': '400', 'price': '4' },
// { 'id': '125', 'amt': '500', 'price': '5' }
// ]
String.prototype.dejoseify = function (reviver, fieldSep, rowSep) {
fieldSep = fieldSep || '|';
rowSep = rowSep || '[';
return this.split(rowSep).map(function (a) {
var o = {};
a.split(fieldSep).forEach(function (v, i) {
o[reviver[i.toString()]] = v;
});
return o;
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment