-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
523 lines (464 loc) · 16.8 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
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
'use strict';
var debug = false;
var stack = 'init';
var paths = [];
function unique(arr) {
var hash = {}, result = [];
for ( var i = 0, l = arr.length; i < l; ++i ) {
if ( !hash.hasOwnProperty(arr[i]) ) { //it works with objects! in FF, at least
hash[ arr[i] ] = true;
result.push(arr[i]);
}
}
return result;
}
function prepareSelectors(paths, root) {
if (debug) console.log('[INFO] paths : ' + JSON.stringify(paths));
var sPaths = [];
for (var i = 0; i < paths.length; i++) {
var val = '';
var objPath = paths[i];
var objKeys = Object.keys(objPath);
objKeys.forEach(function(key) {
if (debug) console.log('[INFO] val: ' + val);
var node = objPath[key];
if (node !== null) {
if (isNaN(node)) {
if (node === 'root' && objKeys.indexOf(key) === 0) { // check if the first node value is "root"
val += node.toString();
} else {
val += '[\'' + node.toString().replace('\'', '\\\'') + '\']';
}
} else {
val += '[' + node.toString() + ']';
}
}
});
var sPath = val.replace(/^root/g, root).replace(/\.\[/g, '[');
sPaths.push(sPath)
}
paths = [];
if (debug) console.log('[INFO] sPaths : ' + JSON.stringify(sPaths));
return unique(sPaths);
}
function pushState(value) {
var count = Object.keys(stack).length;
stack[count] = value;
if (debug) console.log('[INFO] PUSHed ' + value + ' : ' + JSON.stringify(stack));
}
function popState(marker) {
var count = Object.keys(stack).length;
if (count > 1) {
var last_element = count - 1;
var pop_elem = stack[last_element];
delete stack[last_element];
if (debug) console.log('[INFO] POPed ' + pop_elem + ' from ' + marker + ': ' + JSON.stringify(stack));
}
}
function savePath(stack) {
if ((paths.indexOf(stack) === -1) || paths.length === 0) {
if (debug) console.log('[INFO] Pushing ' + JSON.stringify(stack) + ' in Paths');
paths[paths.length] = JSON.parse(JSON.stringify(stack));
if (debug) console.log('[INFO] Paths: ' + JSON.stringify(paths));
}
}
function isObjEqual(a, b) {
var aProps = Object.getOwnPropertyNames(a);
var bProps = Object.getOwnPropertyNames(b);
if (aProps.length !== bProps.length) {
return false;
}
for (var i = 0; i < aProps.length; i++) {
var propName = aProps[i];
if (a[propName] !== b[propName]) {
return false;
}
}
return true;
}
function findInArray(varArray, needle) {
if (debug) console.log('================ENTERED {findInArray}================');
var found = false;
if (needle instanceof Array && varArray.join() === needle.join()) {
if (debug) console.log('[INFO] Matched Array in {findInArray} IF ' + JSON.stringify(needle) + ' in ' + JSON.stringify(stack));
found = true;
}
for (var item in varArray) {
if (debug) console.log('[INFO] Working Array\'s element ' + item);
pushState(item);
if (needle === varArray[item]) {
if (debug) console.log('[INFO] Found in {findInArray} IF ' + needle + ' in ' + JSON.stringify(stack));
found = true;
} else if (typeof(varArray[item]) === 'object') {
if (debug) console.log('[INFO] in {findInArray} ELSE IF ');
if (varArray[item] instanceof Array) {
if (findInArray(varArray[item], needle)) {
if (debug) console.log('[INFO] found in {findInArray}:{findInArray} ELSE IF');
found = true;
}
} else {
if (findInObject(varArray[item], needle)) {
if (debug) console.log('[INFO] found in {findInArray}:{findInObject} ELSE IF');
found = true;
}
}
} else {
if (debug) console.log('[INFO] in {findInArray} ELSE');
if (debug) console.log('===========LEFT {findInArray}================');
if (searchInObject(varArray[item], needle)) {
if (debug) console.log('[INFO] found in {findInArray} ELSE');
found = true;
} else {
if (debug) console.log('================ENTERED {findInArray}================');
}
}
if (found) {
savePath(stack);
popState('{findInArray}-found');
found = false;
}
}
popState('{findInArray}');
if (debug) console.log('===========LEFT {findInObject}================');
return found;
}
function findInObject(varObject, needle) {
if (debug) console.log('================ENTERED {findInObject}================');
var found = false;
if (typeof(needle) === 'object' && !(needle instanceof Array) && isObjEqual(needle, varObject)) {
if (debug) console.log('[INFO] Matched Object in {findInObject} IF ' + JSON.stringify(needle) + ' in ' + JSON.stringify(stack));
found = true;
}
for (var item in varObject) {
if (debug) console.log('[INFO] Working Object\'s element ' + item);
pushState(item);
if ((item === needle) || (varObject[item] === needle)) {
if (debug) console.log('[INFO] in {findInObject} IF ');
if (debug) console.log('[INFO] Found in {findInObject} IF ' + needle + ' in ' + JSON.stringify(stack));
if (debug) console.log('===========LEFT {findInObject}================');
found = true;
if (found) {
savePath(stack);
// popState('{findInObject}-found');
found = false;
}
}
if (typeof(varObject[item]) === 'object') {
if (debug) console.log('[INFO] in {findInObject} ELSE IF ');
if (varObject[item] instanceof Array) {
if (findInArray(varObject[item], needle)) {
if (debug) console.log('[INFO] found in {findInObject}:{findInArray} ELSE IF');
found = true;
}
} else {
if (findInObject(varObject[item], needle)) {
if (debug) console.log('[INFO] found in {findInObject}:{findInObject} ELSE IF');
found = true;
}
}
} else {
if (debug) console.log('[INFO] in {findInObject} ELSE');
if (debug) console.log('===========LEFT {findInObject}================');
if (searchInObject(varObject[item], needle)) {
if (debug) console.log('[INFO] found in {findInObject} ELSE');
found = true;
} else {
if (debug) console.log('================ENTERED {findInObject}================');
}
}
if (found) {
savePath(stack);
popState('{findInObject}-found');
found = false;
}
}
popState('{findInObject}');
if (debug) console.log('===========LEFT {findInObject}================');
return found;
}
function searchInObject(haystack, needle) {
if (debug) console.log('================ENTERED {search}================');
if (stack === 'init') {
stack = {
0: 'root'
};
}
var type = typeof(haystack);
switch (type) {
case 'object':
if (haystack instanceof Array) {
if (debug) console.log('===========LEFT {search} to {findInArray}================');
var result = findInArray(haystack, needle);
} else {
if (debug) console.log('===========LEFT {search} to {findInObject}================');
var result = findInObject(haystack, needle);
}
break;
default:
if (needle === haystack) {
var result = true;
if (debug) console.log('[search] Found: ' + JSON.stringify(stack));
result = false;
savePath(stack);
}
break;
}
if (result) {
if (debug) console.log('[INFO] (search) Found ' + JSON.stringify(needle) + ' in ' + JSON.stringify(result));
if (debug) console.log('===========LEFT {search}================');
return true;
}
popState(stack, '{search}');
if (debug) console.log('===========LEFT {search}================');
return false;
}
function getSibling(selector, json, direction) {
//replace the original object's literal name with "json"
var strOriginalContext = selector.substring(0, selector.indexOf('['));
selector = selector.replace(strOriginalContext, "json");
if (!selector || !json || !direction) return undefined;
var found = false;
var nextSiblingValue = null;
if (selector === undefined) return undefined;
var index = selector.split('[').pop(-1).split(']')[0];
var bookmark = parseInt(index);
if (isNaN(bookmark)) {
bookmark = index.replace(/^'/gi, '').replace(/'$/gi, '');
}
if (debug) console.log('selector: ' + selector);
if (debug) console.log('bookmark: ' + bookmark);
var parentSelector = getParentNode(selector);
if (debug) console.log('parent before eval: ' + parentSelector);
var parentObject = eval(parentSelector);
var that = this;
if (debug) console.log('parent after eval: ' + JSON.stringify(parentObject));
var keys = Object.keys(parentObject);
if (debug) console.log('keys: ' + JSON.stringify(keys));
if (debug) console.log('direction: ' + direction);
switch (direction) {
case 'previous':
if (!isNaN(bookmark)) {
var index = bookmark - 1;
index = index < 0 ? undefined : index;
if (index === undefined) return undefined;
var strNewContext = parentSelector.substring(0, parentSelector.indexOf('['));
parentSelector = parentSelector.replace("json", strOriginalContext);
return parentSelector + '[' + index + ']';
} else {
for (var i = 0; i < keys.length; i++) {
if (keys[i] === bookmark) {
if (!keys[i - 1]) return undefined;
var strNewContext = parentSelector.substring(0, parentSelector.indexOf('['));
parentSelector = parentSelector.replace("json", strOriginalContext);
return parentSelector + '[\'' + keys[i - 1] + '\']';
}
}
}
break;
case 'next':
if (!isNaN(bookmark)) {
var index = bookmark + 1;
index = index >= parentObject.length ? undefined : index
if (index === undefined) return undefined;
var strNewContext = parentSelector.substring(0, parentSelector.indexOf('['));
parentSelector = parentSelector.replace("json", strOriginalContext);
return parentSelector + '[' + index + ']';
} else {
for (var i = 0; i < keys.length; i++) {
if (keys[i] === bookmark) {
if (!keys[i + 1]) return undefined;
var strNewContext = parentSelector.substring(0, parentSelector.indexOf('['));
parentSelector = parentSelector.replace("json", strOriginalContext);
return parentSelector + '[\'' + keys[i + 1] + '\']';
}
}
}
break;
}
}
// Duplicate definition of getParent to deal with scoping issues
function getParentNode(strSelector) {
if (strSelector.endsWith(']')) {
if (debug) console.log('getParentNode: ' + strSelector.substring(0, strSelector.lastIndexOf('[')));
return strSelector.substring(0, strSelector.lastIndexOf('['));
} else {
if (debug) console.log('getParentNode: ' + strSelector.substring(0, strSelector.lastIndexOf('.')));
return strSelector.substring(0, strSelector.lastIndexOf('.'));
}
}
function isSelectorArray(strSelector) {
if (strSelector.endsWith(']')) {
if (debug) console.log('isSelectorArray: ' + true);
return true;
} else {
if (debug) console.log('isSelectorArray: ' + false);
return false;
}
}
function getCurrentIndex(strSelector) {
var startPos = strSelector.lastIndexOf('[') + 1;
var endPos = strSelector.length - 1;
if (isSelectorArray(strSelector)) {
if (debug) console.log('getCurrentIndex: ' + parseInt(strSelector.substring(startPos, endPos)));
return parseInt(strSelector.substring(strSelector.lastIndexOf('[') + 1, strSelector.length - 1));
} else return undefined;
}
function Element(path, haystack) {
this.path = path;
this.obj = haystack;
}
Element.prototype.key = function() {
var selector = this.path;
var index = selector.split('[').pop(-1).split(']')[0];
var bookmark = parseInt(index);
if (isNaN(bookmark)) {
bookmark = index.replace(/^'/gi, '').replace(/'$/gi, '');
}
return bookmark;
};
Element.prototype.parent = function(n = 1) {
if (!this.path) return undefined;
var selector = this.path;
if (selector.endsWith(']')) {
selector = selector.substring(0, selector.lastIndexOf('['));
} else {
selector = selector.substring(0, selector.lastIndexOf('.'));
}
if (n > 1) {
var prntNParent = new Element(selector, this.obj);
var prntNIter = '';
for (var i = 0; i < n - 1; i++) {
prntNIter += '.parent()';
}
try {
var prntNResult = eval("prntNParent" + prntNIter);
} catch (e) {
if (e instanceof TypeError) {
return undefined;
}
}
return prntNResult;
}
return new Element(selector, this.obj);
};
Element.prototype.val = function() {
if (!this.path || !this.obj) return undefined;
var rootObject = this.path.replace(this.path.substring(0, this.path.indexOf('[')), 'this.obj');
return eval(rootObject);
};
Element.prototype.next = function(n = 1) {
if (!this.path || !this.obj) return undefined;
if (n > 1) {
var nxtNIter = '';
var nxtNnext = new Element(getSibling(this.path, this.obj, 'next'), this.obj);
for (var i = 0; i <= n - 1; i++) {
nxtNIter += '.next()';
}
try {
var nxtNResult = eval('nxtNnext' + nxtNIter);
} catch (e) {
if (e instanceof TypeError) {
return undefined;
}
}
return nxtNResult;
}
return new Element(getSibling(this.path, this.obj, 'next'), this.obj);
};
Element.prototype.prev = function(n = 1) {
if (!this.path || !this.obj) return undefined;
if (n > 1) {
var prvNIter = '';
var prvNPrev = new Element(getSibling(this.path, this.obj, 'previous'), this.obj);
for (var i = 0; i < n - 1; i++) {
prvNIter += '.prev()';
}
try {
var prvNResult = eval('prvNPrev' + prvNIter);
} catch (e) {
if (e instanceof TypeError) {
return undefined;
}
}
return prvNResult;
}
return new Element(getSibling(this.path, this.obj, 'previous'), this.obj);
};
Element.prototype.addAfter = function(toInsert) {
if (!toInsert) return undefined;
if (debug) console.log('this.path: ' + this.path);
if (isSelectorArray(this.path)) {
var currentIndex = getCurrentIndex(this.path) + 1;
if (debug) console.log('currentIndex: ' + currentIndex);
if (debug) console.log(getParentNode(this.path) + ".splice(" + currentIndex + ", 0, " + JSON.stringify(toInsert) + ")");
var newSelector = getParentNode(this.path);
newSelector = newSelector.replace(this.path.substring(0, this.path.indexOf('[')), 'this.obj');
if (debug) console.log(newSelector);
eval(newSelector + ".splice(" + currentIndex + ", 0, " + toInsert + ")");
}
return new Element(getSibling(this.path, this.obj, 'next'), this.obj);
};
Element.prototype.addBefore = function(toInsert) {
if (!toInsert) return undefined;
if (isSelectorArray(this.path)) {
var currentIndex = getCurrentIndex(this.path) - 1;
if (debug) console.log(getParentNode(this.path) + ".splice(" + currentIndex + ", 0, " + JSON.stringify(toInsert) + ")");
var newSelector = getParentNode(this.path);
newSelector = newSelector.replace(this.path.substring(0, this.path.indexOf('[')), 'this.obj');
if (debug) console.log('addBefore.newSelector: ' + newSelector);
eval(newSelector + ".splice(" + currentIndex + ", 0, " + toInsert + ")");
}
return new Element(getSibling(this.path, this.obj, 'previous'), this.obj);
};
Element.prototype.replace = function(value) {
if (!value) return undefined;
var newSelector = this.path;
newSelector = newSelector.replace(this.path.substring(0, this.path.indexOf('[')), 'this.obj');
if (typeof value === "string") {
if (debug) console.log('assign str: ' + newSelector + ' = \"' + value + '\";');
eval(newSelector + ' = \"' + value + '\";');
} else if (typeof value === "object") {
if (debug) console.log('assign obj: ' + newSelector + ' = ' + JSON.stringify(value) + ';');
eval(newSelector + ' = ' + JSON.stringify(value) + ';');
} else {
eval(newSelector + ' = ' + value.toString() + ';');
}
return new Element(this.path, this.obj);
};
var tweezr = {
findAll: function(keyword, objHaystack, strContext, callback) {
paths = [];
var Elements = [];
searchInObject(objHaystack, keyword); // paths[] enumerated
var allSelectors = prepareSelectors(paths, strContext);
for (var i = 0; i < allSelectors.length; i++) {
Elements.push(new Element(allSelectors[i], objHaystack));
}
if (callback) {
callback(Elements);
} else {
return Elements;
}
},
findAndReplaceAll: function(data, find, replace, callback) {
paths = [];
var json = typeof data === 'string' ? JSON.parse(data) : typeof data === 'object' ? data : {};
searchInObject(json, find);
var selectors = prepareSelectors(paths, 'json');
selectors.forEach(function(selector) {
eval(selector + '=\'' + replace + '\'');
});
if (callback) {
callback(json);
} else {
return json;
}
}
};
module.exports = {
init: function(options) {
options = options || {};
debug = options && options.debug || false;
return tweezr;
}
};