source: node_modules/undefsafe/lib/undefsafe.js@ 81bc7da

finki-main main
Last change on this file since 81bc7da was 81bc7da, checked in by Klimentina Efremova <klimentina08642@…>, 3 months ago

Initial commit

  • Property mode set to 100644
File size: 2.5 KB
Line 
1'use strict';
2
3function undefsafe(obj, path, value, __res) {
4 // I'm not super keen on this private function, but it's because
5 // it'll also be use in the browser and I wont *one* function exposed
6 function split(path) {
7 var res = [];
8 var level = 0;
9 var key = '';
10
11 for (var i = 0; i < path.length; i++) {
12 var c = path.substr(i, 1);
13
14 if (level === 0 && (c === '.' || c === '[')) {
15 if (c === '[') {
16 level++;
17 i++;
18 c = path.substr(i, 1);
19 }
20
21 if (key) {
22 // the first value could be a string
23 res.push(key);
24 }
25 key = '';
26 continue;
27 }
28
29 if (c === ']') {
30 level--;
31 key = key.slice(0, -1);
32 continue;
33 }
34
35 key += c;
36 }
37
38 res.push(key);
39
40 return res;
41 }
42
43 // bail if there's nothing
44 if (obj === undefined || obj === null) {
45 return undefined;
46 }
47
48 var parts = split(path);
49 var key = null;
50 var type = typeof obj;
51 var root = obj;
52 var parent = obj;
53
54 var star =
55 parts.filter(function(_) {
56 return _ === '*';
57 }).length > 0;
58
59 // we're dealing with a primitive
60 if (type !== 'object' && type !== 'function') {
61 return obj;
62 } else if (path.trim() === '') {
63 return obj;
64 }
65
66 key = parts[0];
67 var i = 0;
68 for (; i < parts.length; i++) {
69 key = parts[i];
70 parent = obj;
71
72 if (key === '*') {
73 // loop through each property
74 var prop = '';
75 var res = __res || [];
76
77 for (prop in parent) {
78 var shallowObj = undefsafe(
79 obj[prop],
80 parts.slice(i + 1).join('.'),
81 value,
82 res
83 );
84 if (shallowObj && shallowObj !== res) {
85 if ((value && shallowObj === value) || value === undefined) {
86 if (value !== undefined) {
87 return shallowObj;
88 }
89
90 res.push(shallowObj);
91 }
92 }
93 }
94
95 if (res.length === 0) {
96 return undefined;
97 }
98
99 return res;
100 }
101
102 if (Object.getOwnPropertyNames(obj).indexOf(key) == -1) {
103 return undefined;
104 }
105
106 obj = obj[key];
107 if (obj === undefined || obj === null) {
108 break;
109 }
110 }
111
112 // if we have a null object, make sure it's the one the user was after,
113 // if it's not (i.e. parts has a length) then give undefined back.
114 if (obj === null && i !== parts.length - 1) {
115 obj = undefined;
116 } else if (!star && value) {
117 key = path.split('.').pop();
118 parent[key] = value;
119 }
120 return obj;
121}
122
123if (typeof module !== 'undefined') {
124 module.exports = undefsafe;
125}
Note: See TracBrowser for help on using the repository browser.