Commit 2683c204 2683c20417e16eb2277df7b7c7d0bbdfabc12ca8 by Nicolas Perriault

added utils.getPropertyPath()

1 parent 918e9906
......@@ -128,6 +128,32 @@
exports.format = format;
/**
* Retrieves the value of an Object foreign property using a bot-separated
* path string.
*
* Beware, this function doesn't handle object key names containing a dot.
*
* @param Object obj The source object
* @param String path Dot separated path, eg. "x.y.z"
*/
function getPropertyPath(obj, path) {
if (!isObject(obj) || !isString(path)) {
return undefined;
}
var value = obj;
path.split('.').forEach(function(property) {
if (typeof value === "object" && property in value) {
value = value[property];
} else {
value = undefined;
return;
}
});
return value;
}
exports.getPropertyPath = getPropertyPath;
/**
* Inherit the prototype methods from one constructor into another.
*
* @param {function} ctor Constructor function which needs to inherit the
......
......@@ -29,6 +29,43 @@ t.comment('fillBlanks()');
}
})();
t.comment('getPropertyPath()');
(function() {
testCases = [
{
input: utils.getPropertyPath({}, 'a.b.c'),
output: undefined
},
{
input: utils.getPropertyPath([1, 2, 3], 'a.b.c'),
output: undefined
},
{
input: utils.getPropertyPath({ a: { b: { c: 1 } }, c: 2 }, 'a.b.c'),
output: 1
},
{
input: utils.getPropertyPath({ a: { b: { c: 1 } }, c: 2 }, 'a.b.x'),
output: undefined
},
{
input: utils.getPropertyPath({ a: { b: { c: 1 } }, c: 2 }, 'a.b'),
output: { c: 1 }
},
{
input: utils.getPropertyPath({ 'a-b': { 'c-d': 1} }, 'a-b.c-d'),
output: 1
},
{
input: utils.getPropertyPath({ 'a.b': { 'c.d': 1} }, 'a.b.c.d'),
output: undefined
}
];
testCases.forEach(function(testCase) {
t.assertEquals(testCase.input, testCase.output, 'getPropertyPath() gets a property using a path');
});
})();
t.comment('isArray()');
(function() {
t.assertEquals(utils.isArray([]), true, 'isArray() checks for an Array');
......