Created
December 11, 2012 15:40
-
-
Save mirlord/4259429 to your computer and use it in GitHub Desktop.
tpl3d.js proof of concept
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var flatObj = { | |
simple_str: 'simple', | |
stringified_array: 'simple,array', | |
'a.1': 'item first', | |
'a.0': 'item second' | |
'obj.field': '1.0' | |
}; | |
var treeTemplate = { | |
unstringified: [ | |
'stringified_array', | |
function (value) { | |
value.split(','); | |
} | |
], | |
aa: /a\.\d+/, | |
ab: [ | |
/a\.\d+/, | |
null, | |
function (key) { | |
return key.split('.')[1]; | |
} | |
] | |
obj: { | |
field_original: 'obj.field', | |
field_scalar: [ | |
'obj.field', | |
function (value) { | |
parseInt(value); | |
} | |
] | |
} | |
}; | |
// the same with router-like API | |
var marshal = function (m) { | |
m.cmap('stringified_array', m.toJSON, 'unstringified'); | |
m.mmap('a', function (key, self) { // it will be a out-of-the-box helpers for this | |
var r = {}, i; | |
for (i in self.aa) { | |
r[key + '.' + i] = self.aa[i]; | |
} | |
return r; | |
}); | |
m.map('obj.field', ['obj', 'field_orig']); | |
}; | |
var treeObj = //flat2tree(flatObj, treeTemplate); | |
{ | |
simple_str: 'simple', // as is | |
unstringified: ['simple', 'array'], | |
aa: ['item second', 'item first'], // in order of sorted keys | |
ab: { | |
'1': 'item first', | |
'0': 'item second' | |
}, | |
obj: { | |
field_original: '1.0', | |
field_scalar: 1 | |
} | |
}; | |
var flatTemplate = { | |
stringified_array: [ | |
'unstringified', | |
function (value) { | |
return value.join(','); | |
} | |
], | |
a: 'ab', // most unclear momnent | |
'obj.field': [ | |
null, | |
function (self) { | |
return self.obj.field_original; | |
} | |
] | |
}; | |
// the same with router-like API | |
var unmarshal = function (u) { | |
u.map('simple_str'); // redundant, it's a default | |
u.map('simple_str', 'copy_of_simple_str'); | |
u.cmap('stringified_array', u.fromJSON, 'unstringified'); | |
u.amap(/a\.\d+/, 'aa'); | |
u.map(/a\.\d+/, function (k) { | |
return ['ab', k.split('.')[1]]; | |
}); | |
u.map('obj.field', ['obj', 'field_orig']); | |
u.cmap('obj.field', u.scalar, ['obj', 'field_scalar']); | |
u.tcmap(/obj\..+/, parseInt, '.'); | |
}; | |
var result = // tree2flat(treeObj, treeTemplate); | |
{ | |
simple_str: 'simple', | |
stringified_array: 'simple,array', | |
'a.1': 'item first', | |
'a.0': 'item second' | |
'obj.field': '1.0' | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment