The following function takes an object of items in the format of
{
'complex-key': 'value',
// Repeat
}
where complex-key
is a key delimited by dots, and returns an object in the form of a tree, where you can access the value by traversing the parts of the complex keys as keys in the object (see examples below).
The function
function createMessages(items) {
var result = {};
Object.keys(items).forEach(function(key) {
var keyParts = key.split('.');
var currentObj = result;
while (keyParts.length > 0) {
var currentKey = keyParts.shift();
if (keyParts.length === 0) {
var currentItems = {};
if (currentObj[currentKey]) {
currentItems = currentObj[currentKey];
}
currentObj[currentKey] = function() { return items[key]; };
Object.keys(currentItems).forEach(function(currentItemKey) {
currentObj[currentKey][currentItemKey] = currentItems[currentItemKey];
});
}
else if (!currentObj[currentKey]) { currentObj[currentKey] = {}; }
currentObj = currentObj[currentKey];
}
});
return result;
}
Examples
var message1 = createMessages({'a.b.c.d': 42});
console.log(message1.a.b.c.d() === 42); // true
var message2 = createMessages({'a.b.c.d': 42, 'a.b.c.e': 43});
console.log(message2.a.b.c.d() === 42); // true
console.log(message2.a.b.c.e() === 43); // true
var message3 = createMessages({'a.b.c.d': 42, 'a.b.c': 43});
console.log(message3.a.b.c() === 43); // true
console.log(message3.a.b.c.d() === 42); // true (properties on the functions)
The current function looks overly bloated and inefficient (with \$O(n\times m)\$ at best, and \$O(n\times m^2)\$ at worst). While this is going to be used for test code only, and to small objects only (no more than 10 keys), I would still want to find a way to make it prettier and more efficient. Would appreciate any and all help.