-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
54 lines (43 loc) · 1.07 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/**
* Module dependencies.
* @api private
*/
var clone = require('bredele-clone');
/**
* Expose Middleware
*/
module.exports = function(store) {
/**
* Set and get path.
* example:
* store.path('country.canada'); //get
* store.path('country.canada', 'france');
* store.path('name.3.2', 'olivier'); //works with arrys
*
* @param {String} name
* @param {Any} val
* @api public
*/
store.path = function(name, val) {
var path = name.split('.'),
attr = clone(store.get(path[0]));
if(val == undefined) {
for(var i = 1, l = path.length; i < l; i++) {
attr = attr[path[i]];
}
return attr;
} else {
var cache = attr;
for(var j = 1, h = path.length - 1; j < h; j++) {
var prop = path[j];
if(!cache.hasOwnProperty(prop) || (typeof cache[prop] !== 'object')) {
cache[prop] = {};
}
cache = cache[prop];
}
cache[path[j]] = val;
//TODO:L refactor, if no '.' just set with val
store.set(path[0], h === 0 ? val : attr);
}
};
};