Add new code new version
[sdc.git] / openecomp-ui / src / nfvo-utils / json / JSONPointer.js
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 const JSONPointer = {
22
23         extractParentPointer(pointer) {
24                 return pointer.replace(/\/[^\/]+$/, '');
25         },
26
27         extractLastPart(pointer) {
28                 const [,lastPart] = pointer.match(/\/([^\/]+)$/) || [];
29                 return lastPart;
30         },
31
32         extractParts(pointer) {
33                 return pointer.split('/').slice(1)
34                         .map(part => part.replace(/~1/g, '/'))
35                         .map(part => part.replace(/~0/g, '~'));
36         },
37
38         getValue(object, pointer) {
39                 let parts = JSONPointer.extractParts(pointer);
40                 return parts.reduce((object, part) => object && object[part], object);
41         },
42
43         setValue(object, pointer, value) {
44                 let clone = obj => Array.isArray(obj) ? [...obj] : {...obj};
45
46                 let parts = JSONPointer.extractParts(pointer),
47                         newObject = clone(object),
48                         subObject = object,
49                         subNewObject = newObject;
50
51                 for(let i = 0, n = parts.length - 1; i < n; ++i) {
52                         let nextSubObject = subObject && subObject[parts[i]];
53                         subNewObject = subNewObject[parts[i]] = nextSubObject ? clone(nextSubObject) : {};
54                         subObject = nextSubObject;
55                 }
56                 subNewObject[parts[parts.length - 1]] = value;
57
58                 return newObject;
59         }
60 };
61
62 export default JSONPointer;