-
Notifications
You must be signed in to change notification settings - Fork 3
/
vpo.js
97 lines (82 loc) · 2.47 KB
/
vpo.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
'use strict';
(function(vpo) {
function setValueByPath(object, path, value) {
var splitPath = path.split('.');
var key = splitPath.shift();
if (splitPath.length > 0) {
object[key] = object[key] || ((!isNaN(parseInt(splitPath[0], 10))) ? [] : {});
setValueByPath(object[key], splitPath.join('.'), value);
} else {
object[key] = value;
}
}
function getValueByPath(object, path, fallback) {
var nextPath = '';
var splitPath = path.split('.');
if (object && object.hasOwnProperty(splitPath[0])) {
if (splitPath.length > 1) {
nextPath = path.replace(splitPath[0] + '.', '');
return getValueByPath(object[splitPath[0]], nextPath, fallback);
} else {
return object[splitPath[0]];
}
}
return fallback;
}
function getPathByMatchingValue(obj, value) {
var finalPath = '';
var trace = [];
var iterator = function iterator(obj, value) {
// find all object keys
for (var key in obj) {
// add it to the stack
trace.push(key);
if (typeof obj[key] === 'object') {
// call the recursive function
iterator(obj[key], value);
trace.pop();
} else {
if (obj[key] !== value) {
// remove it from the stack
trace.pop();
} else {
// yay, found him. print the stack to finalPath
// trace.pop();
finalPath = trace.join('.');
}
}
}
};
iterator(obj, value);
return finalPath;
}
function getSome(object, paths, fallback) {
var result = undefined;
paths.some(function(path) {
return (result = getValueByPath(object, path));
});
return (result !== undefined) ? result : fallback;
}
function pick(obj, paths) {
return paths.reduce(function(result, path) {
var value = getValueByPath(obj, path, undefined);
if (value !== undefined) {
setValueByPath(result, path, value);
}
return result;
}, {});
}
vpo.set = setValueByPath;
vpo.get = getValueByPath;
vpo.getSome = getSome;
vpo.getByValue = getPathByMatchingValue;
vpo.pick = pick;
vpo.setOnObjectPrototype = function() {
Object.prototype.set = function(path, value) {
setValueByPath(this, path, value);
};
Object.prototype.get = function(path, fallback) {
return getValueByPath(this, path, fallback);
};
};
})( (typeof exports === 'undefined') ? this['vpo'] = {} : exports);