Commit 2683c204 2683c20417e16eb2277df7b7c7d0bbdfabc12ca8 by Nicolas Perriault

added utils.getPropertyPath()

1 parent 918e9906
...@@ -128,6 +128,32 @@ ...@@ -128,6 +128,32 @@
128 exports.format = format; 128 exports.format = format;
129 129
130 /** 130 /**
131 * Retrieves the value of an Object foreign property using a bot-separated
132 * path string.
133 *
134 * Beware, this function doesn't handle object key names containing a dot.
135 *
136 * @param Object obj The source object
137 * @param String path Dot separated path, eg. "x.y.z"
138 */
139 function getPropertyPath(obj, path) {
140 if (!isObject(obj) || !isString(path)) {
141 return undefined;
142 }
143 var value = obj;
144 path.split('.').forEach(function(property) {
145 if (typeof value === "object" && property in value) {
146 value = value[property];
147 } else {
148 value = undefined;
149 return;
150 }
151 });
152 return value;
153 }
154 exports.getPropertyPath = getPropertyPath;
155
156 /**
131 * Inherit the prototype methods from one constructor into another. 157 * Inherit the prototype methods from one constructor into another.
132 * 158 *
133 * @param {function} ctor Constructor function which needs to inherit the 159 * @param {function} ctor Constructor function which needs to inherit the
......
...@@ -29,6 +29,43 @@ t.comment('fillBlanks()'); ...@@ -29,6 +29,43 @@ t.comment('fillBlanks()');
29 } 29 }
30 })(); 30 })();
31 31
32 t.comment('getPropertyPath()');
33 (function() {
34 testCases = [
35 {
36 input: utils.getPropertyPath({}, 'a.b.c'),
37 output: undefined
38 },
39 {
40 input: utils.getPropertyPath([1, 2, 3], 'a.b.c'),
41 output: undefined
42 },
43 {
44 input: utils.getPropertyPath({ a: { b: { c: 1 } }, c: 2 }, 'a.b.c'),
45 output: 1
46 },
47 {
48 input: utils.getPropertyPath({ a: { b: { c: 1 } }, c: 2 }, 'a.b.x'),
49 output: undefined
50 },
51 {
52 input: utils.getPropertyPath({ a: { b: { c: 1 } }, c: 2 }, 'a.b'),
53 output: { c: 1 }
54 },
55 {
56 input: utils.getPropertyPath({ 'a-b': { 'c-d': 1} }, 'a-b.c-d'),
57 output: 1
58 },
59 {
60 input: utils.getPropertyPath({ 'a.b': { 'c.d': 1} }, 'a.b.c.d'),
61 output: undefined
62 }
63 ];
64 testCases.forEach(function(testCase) {
65 t.assertEquals(testCase.input, testCase.output, 'getPropertyPath() gets a property using a path');
66 });
67 })();
68
32 t.comment('isArray()'); 69 t.comment('isArray()');
33 (function() { 70 (function() {
34 t.assertEquals(utils.isArray([]), true, 'isArray() checks for an Array'); 71 t.assertEquals(utils.isArray([]), true, 'isArray() checks for an Array');
......