/
DataObject.js
99 lines (82 loc) · 2 KB
/
DataObject.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
98
99
'use strict';
var isString = require('lodash/isString');
var isArray = require('lodash/isArray');
var get = require('lodash/get');
var setWith = require('lodash/setWith');
var unset = require('lodash/unset');
var oo = require('../../util/oo');
/*
An object that can be access via path API.
@class
@param {object} [obj] An object to operate on
@example
var obj = new DataObject({a: "aVal", b: {b1: 'b1Val', b2: 'b2Val'}});
*/
function DataObject(root) {
if (root) {
this.__root__ = root;
}
}
DataObject.Prototype = function() {
this.getRoot = function() {
if (this.__root__) {
return this.__root__;
} else {
return this;
}
};
/**
Get value at path
@return {object} The value stored for a given path
@example
obj.get(['b', 'b1']);
=> b1Val
*/
this.get = function(path) {
if (!path) {
return undefined;
}
if (isString(path)) {
return this.getRoot()[path];
}
if (arguments.length > 1) {
path = Array.prototype.slice(arguments, 0);
}
if (!isArray(path)) {
throw new Error('Illegal argument for DataObject.get()');
}
return get(this.getRoot(), path);
};
this.set = function(path, value) {
if (!path) {
throw new Error('Illegal argument: DataObject.set(>path<, value) - path is mandatory.');
}
if (isString(path)) {
this.getRoot()[path] = value;
} else {
setWith(this.getRoot(), path, value);
}
};
this.delete = function(path) {
if (isString(path)) {
delete this.getRoot()[path];
} else if (path.length === 1) {
delete this.getRoot()[path[0]];
} else {
var success = unset(this.getRoot(), path);
if (!success) {
throw new Error('Could not delete property at path' + path);
}
}
};
this.clear = function() {
var root = this.getRoot();
for (var key in root) {
if (root.hasOwnProperty(key)) {
delete root[key];
}
}
};
};
oo.initClass(DataObject);
module.exports = DataObject;