-
Notifications
You must be signed in to change notification settings - Fork 0
/
EZprototypes.js
6767 lines (5876 loc) · 237 KB
/
EZprototypes.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
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*__________________________________________________________________________________________________
Flagship or salient differiencators are:
-returns pseudo elementwhen no element match selector to avoid js error
when following assumes element(s) are always returned
-built-in unit testing and documentation
-works as standalone lightwieght jquery-like library or as jquery wrapper
-easy error and/or stacktrack repoting
----------------------------------------------------------------------------------------------------
For new organizational structure, functions moving from EZ.core to one of the following files:
EZ/RZprototypes.js (same file) and should also match EASY.prototypes.js
prototypes and related functions
EZ/RZgetset.js (same file) future replacement for EASY.core.js::EZ(...)
EZ/RZcommon.js (same file) common functions from RevizeCommon.js non-dreamweaver specific
and partial port of EASY.js functions
EZdwutils.js (latest) Dreamweaver/Revize specific functions: e.g. getDOM()
RZdwutils.js (legacy) old versions of DW functions used by Revize Extension
-------------------------------------------------------------------------------------------------
-change all is (el == null) --> (el == null)
-test EZ.isEl & EZ.isNonElObject
EZ stubs, prototypes and related or core functions --
shared between DW extension developer toolkit api and EZ javascript libaray:
stubs: EZ(), EZ._(), EZ.$(), EZ.css(), EZ.get(), EZ.set() and EZ.val()
calls to: EZgetEl(), EZgetStyle(), EZgetValue(), EZsetValue() . . .
defined in EZbasics.js along with supporting functions
functions: is(), isEmpty(), isNone(), isTrueLike(), isFalseLike(),
isArray(), isArrayLike(), toArray(), toFloat(), toInt(),
clip(), format(), left(), right(), trim(), matchPlus(), matches() . . .
Object prototypes defined to avoid need to check hasOwnProperty in loops.
Function.prototype.bindTODO = function bindEZprototypeFunction(scope)
{ //Breaks EZsortable drag
var fn = this;
return function () { return fn.apply(scope) };
}
__________________________________________________________________________________________________*/
/*--------------------------------------------------------------------------------------------------
EZ(el,options) -- primary EZ Object defined as Function
returns single element or Array of elements if el is Array of selectors.
--------------------------------------------------------------------------------------------------*/
function EZ(el, options)
{
var args = [].slice.call(arguments).concat([ {defaults:{legacy:false}} ]);
return EZgetEl.apply(this, args);
return EZ.getEl(el, options == false); //from unit test
}
/*--------------------------------------------------------------------------------------------------
EZ variants -- stubs to EZgetEl(...)
--------------------------------------------------------------------------------------------------*/
/**
* EZ$: return all elements matching all selector(s)
*/
EZ$ = function EZ$()
{
var args = [].slice.call(arguments).concat([ {defaults:{all:true}} ]);
return EZgetEl.apply(this, args);
}
EZ.$ = EZ$;
/**
* EZ_: return single element even if selector is Array.
* TODO: depricate to eliminate clutter
*/
EZ._ = function EZ_()
{
var args = ([].slice.call(arguments)).concat([ {defaults:{all:false}} ]);
return EZgetEl.apply(this, args);
}
/**
* EZ.nul: return all elements matching selector(s) or null
*/
EZ.nul = function EZnul()
{
var args = [].slice.call(arguments).concat([ {defaults:{notFound:null}} ]);
return EZgetEl.apply(this, args);
}
//_____________________________________________________________________________________________
EZ.test = function()
{
EZ.test.run('#myid', {EZ: {ex:'', note:'' }})
EZ.test.run('<div>', '<div', {EZ: {ex:'', note:'' }})
EZ.test.run('.myclass', {EZ: {ex:'', note:'' }})
EZ.test.run('myid', 'div', 'myclass', {EZ: {ex:'', note:'' }})
// form fields
EZ.test.run('notifyForm:notifySelected', {EZ: {ex:'', note:'' }})
EZ.test.run('@notifyForm:notifySelected', {EZ: {ex:'', note:'' }})
EZ.test.run('@notifyForm:notifySelecte', {EZ: {ex:'', note:'bad name' }})
EZ.test.run('notifySelected', {EZ: {ex:'', note:'' }})
EZ.test.run('@notifySelected', {EZ: {ex:'', note:'' }})
//. . . . . . . . . . . . . . . . . . . . . . . .
}
//_____________________________________________________________________________________________
/**
* unit test stubs -- redefined when EZunit_tests.html loaded
*/
EZ.test.capture = function EZtestCapture() {return false}
EZ.test.capture.mode = false;
EZ.test.debug = function EZtestDebug() {return false}
EZ.test.run = function EZtestRun() {return false}
EZ.testSample = function EZtestSample(arg,other) {return arg}
EZ.testSample.test = function()
{
// EZ.test.run(1, {EZ: {ex:1 }})
EZ.test.run([1,2], {EZ: {ex:[1,2] }})
}
/**
*
*/
EZ.cookie = {
get:function EZcookieGet() {return ''},
set:function EZcookieSet() {return ''}
}
//EZ.cookie = function EZcookie() {};
/**
*
*/
EZ.css = function EZcss()
{
if (!EZ.getStyle) return '';
return EZ.getStyle.apply(this,[].slice.call(arguments));
}
/**
* Stubs for functions with full script in other files
*/
EZ.dom = {};
EZ.json = {};
EZ.event = {};
EZ.util = {};
EZ.getPref = function EZgetPref(key, defaultValue) {return defaultValue};
/*---------------------------------------------------------------------------------------------
Diagnostic and research tool
---------------------------------------------------------------------------------------------*/
EZ.json.nodeLogger = function nodeLogger(key, value)
{
var log = EZ.json.log = EZ.json.log || [];
log.push(
'key=' + JSON.stringify(key).replace(/"/g,'')
+ '\t\t' +
'value=' + JSON.stringify(value) + '\n\t\t' +
JSON.stringify(this).replace(/"/g,'') // parent
);
return value;
}
/*---------------------------------------------------------------------------------------------
EZ.json.parse(value)
Extend navive JSON.parse to support pseudo json created by EZ.json.stringify() for named Array
properties and Regular Expressions -- For Details: see EZ.json.stringify()
Removes \n and quotes Object keys before parsing if necessary. Returns value is not String.
---------------------------------------------------------------------------------------------*/
EZ.json.parse = function EZjson_parse(value)
{
if (typeof(value) != 'string') return value;
value = value.trim();
var pattern = /([{,]\s*)(\w+):(?!=\/)/g;
if (pattern.test(value))
value = value.replace(pattern, '$1"$2":'); //quote keys
if (/\\n/.test(value))
value = value.replace(/\n/g, ''); //remove newlines
if (/\n/.test(value))
value = value.replace(/\n/g, ''); //remove newlines
//======================================
var obj = JSON.parse(value, EZjson_format);
return obj;
//======================================
//__________________________________________________________________________________________
/**
* called for children before parents
if (value.indexOf('@__') != -1) //multiline Strings
{
value = value.replace(/@__\n([\s\S]+?)__@/gi, function(all, str)
{ //drop prefix/suffix
return str.replace(/@\n/g, '\\n'); //unescape @\n --> \\n
});
}
function EZjson_format(key, value)
{
//return RegExp object for string of form "RegExp:/.../gim"
if (typeof(value) == 'string')
{
if (value == '@@undefined@@')
{
return undefined;
}
else if (value.indexOf('RegExp:/') == 0) //RegExp
{
var e;
try
{
var regex = value.match(/^RegExp:\/([\s\S]*)\/([gim]*)/);
if (regex)
return new RegExp(regex[1], regex[2]);
}
catch (e) {}
}
return value;
}
if (typeof(value) == 'string' && value.indexOf('RegExp:/') == 0) //RegExp
*/
function EZjson_format(key, value)
{
//return RegExp object for Object of form "{"RegExp":"/.../gim}"
if (Object.prototype.toString.call(value) === '[object Object]'
&& Object.keys(value).join('') == 'RegExp' && typeof value.RegExp == 'string')
{
var e;
try
{
var regex = value.RegExp(/^\/([\s\S]*)\/([gim]*)/);
if (regex)
return new RegExp(regex[1], regex[2]);
}
catch (e) {}
return value;
}
// if Array and last item is pseudo properties Object of the form:
// {"_____keys____": # {key1: value1, key1: value1, ...}
// remove item from Array and use to create named Array properties.
var isArray = Object.prototype.toString.call(value) === '[object Array]';
while (isArray && value.length)
{
var properties = value[value.length-1];
if (!properties || typeof(properties) != 'object') break;
var keys = Object.keys(properties);
if ((keys.length-1) !== properties['_____keys_____']) break;
keys.forEach(function(key) //transfer key values to Array object
{
if (key != '_____keys_____')
value[key] = properties[key];
});
value.splice(value.length-1, 1); //then delete pseudo Array item
break;
}
return value;
}
}
//_____________________________________________________________________________________________
EZ.json_parse = EZ.json.parse;
EZ.json_parse.test = function()
{
var ex = 'na';
var note = '';
var json = '';
//______________________________________________________________________________
// #1
ex = EZ.global.testdata.include;
note = 'ObjectLike Array with '
+ 'named keys'
jsonHTML();
EZ.test.run(json, {EZ: {ex:ex, note:note}})
//_______________________________________________________________________________
// #2
ex = EZ.global.testdata.person
note = 'Object same as native\n'
+ 'except keys not quoted'
jsonHTML();
EZ.test.run(json, {EZ: {ex:ex, note:note}})
//_______________________________________________________________________________
// #3
ex = EZ.global.testdata.array
note = 'Pure Array -- no item '
+ 'contains an object so: '
+ 'Array is not indented '
+ 'but space after comma'
jsonHTML();
EZ.test.run(json, {EZ: {ex:ex, note:note}})
//_______________________________________________________________________________
// #4
ex = EZ.global.testdata.arraySparse
//ex = ex.replace(/null/, /undefined/)
note = 'Array sparely poulated '
+ 'item[2] undefined but '
+ 'native stringify treats '
+ 'as null'
jsonHTML();
ex[2] = null;
EZ.test.run(json, {EZ: {ex:ex, note:note}})
//_______________________________________________________________________________
// #5
ex = EZ.global.testdata.personArrayLike
note = 'ArrayLike Object: same '
+ 'as native stringify '
+ 'except: keys not quoted '
jsonHTML();
EZ.test.run(json, {EZ: {ex:ex, note:note}})
//_______________________________________________________________________________
// #6
ex = ''; note = 'empty string exactly '
+ 'as native stringify '
jsonHTML();
EZ.test.run(json, {EZ: {ex:ex, note:note}})
//_______________________________________________________________________________
// #7
ex = null; note = 'null exactly same '
+ 'as native stringify '
jsonHTML();
EZ.test.run(json, {EZ: {ex:ex, note:note}})
//_______________________________________________________________________________
// #8
ex = EZ.global.testdata.objectLike;
note = 'ObjectLike Array has\n'
+ 'named keys - IGNORED '
+ 'by native stringify'
jsonHTML();
EZ.test.run(json, {EZ: {ex:ex, note:note}})
//_______________________________________________________________________________
// #9
var a = EZ.global.testdata.array.slice();
a.push(EZ.global.testdata.person)
ex = a;
note = 'Array format same as native when ANY array item contains object '
+ 'except: keys unquoted and spaces after Array item commas'
jsonHTML();
EZ.test.run(json, {EZ: {ex:ex, note:note}})
//_______________________________________________________________________________
// #10
ex = EZ.global.testdata.fuse;
note = 'Fuse Object with embedded ObjectLike include Array with named keys'
jsonHTML();
EZ.test.run(json, {EZ: {ex:ex, note:note}})
//_______________________________________________________________________________
// #11
ex = EZ.global.testdata.arraySparsePlus;
note = 'complex Array with '
+ 'no ObjectLike Arrays '
jsonHTML();
EZ.test.run(json, {EZ: {ex:ex, note:note}})
//_______________________________________________________________________________
// #12
ex = EZ.global.testdata.objectLikeMore;
note = 'complex ObjectLike'
jsonHTML();
EZ.test.run(json, {EZ: {ex:ex, note:note}})
//_______________________________________________________________________________
// #13
ex = /\s*(a|b|c)/gim;
note = 'RegExp Standalone'
jsonHTML();
EZ.test.run(json, {EZ: {ex:ex, note:note}})
//_______________________________________________________________________________
// #14
ex = [/\s*(a|b|c)/gim]; note = 'RegExp in Array'
jsonHTML();
EZ.test.run(json, {EZ: {ex:ex, note:note}})
//_______________________________________________________________________________
// #15
ex = {pattern: /\s*(a|b|c)/gim};
note = 'RegExp in Object'
jsonHTML();
EZ.test.run(json, {EZ: {ex:ex, note:note}})
//_______________________________________________________________________________
// #16
ex = EZ.global.testdata.arraySparsePlus;
note = '20 items'
jsonHTML();
EZ.test.run(json, {EZ: {ex:ex, note:note}})
//_______________________________________________________________________________
// #17
ex = EZ.global.testdata.multiline;
note = 'multiline String'
jsonHTML();
EZ.test.run(json, {EZ: {ex:ex, note:note}})
//_______________________________________________________________________________
function jsonHTML()
{
json = JSON.stringify(ex, null, 4)
note += '<br>native JSON:<br>' + json.replace(/\n/g, '<br>').replace(/ /g, ' ')
json = EZ.stringify(ex);
}
}
/*---------------------------------------------------------------------------------------------
EZ.json.stringify(value, replacer, spaces)
Extend navive JSON.stringify() as follows:
Non-numeric enumerable Array keys are stringified by creating Object of the following form
and adding to the Array as pseudo item:
{
_____keys_____: <keyCount>,
key1: value1,
key2: value2 ...
}
RegExp Objects stringify as a String of the following form:
"RegExp:/\\s*(a|b|c)gim"
Multiline String are formatted in the following form:
@--
John Tyler III, President@
Keys Adventures, Inc@
123 Palms, Suite Q@
Key Largo, FL 80209__@
Array items are only indented on a separate line, if they contain Object, Array, RegExp, multiline
or large String.
Otherwise items formatted together on a single line with a single space after
the comma separator (up to items per line limit)
up to:
NOTE:
EZ.json.parse() removes the pseudo item and uses to create named Array keys,
creates RegExp and converts multiline String to standard json format.
EXAMPLES:
[1, 2, 3, "x", "y', "z", true, false]
-OR-
[
1, 2, 3, true, false,
{
letters: 'abcdefghijklmnopqreswxyz',
numbers: '0123456789'
}
"red", "yellow", "green",
{
_____keys_____: 2,
pattern: "RegExp:/\\s*(a|b|c)/gim",
sisters: ["Pam", "Sandy"]
}
]
ARGUMENTS: same as JSON.stringify
value object to stringify
replacer Array or key names extracted from Object and converted to json. Names prefixed
with minus sign (-) are not extracted -- all others formatted as json.
DOES NOT allow nodeVisitor function. Uses the internal EZformat() function.
spaces Number of spaces to indent each json level or String prefix. If omitted and
replacer is number or string, it defined spaces.
default: 4
TODO:
support nodeVisitor replacer function
support undefined values??
break long list of Array items into multiple lines
REFERRENCE: nice JSON doc
http:https://speakingjs.com/es5/ch22.html
---------------------------------------------------------------------------------------------*/
EZ.json.stringify = function EZstringify(value, replacer, spaces, options)
{
//----- process arguments
if ('object function'.indexOf(typeof replacer) == -1)
{ //replacer omitted -- shift arguments
options = spaces;
spaces = replacer;
replacer = null;
}
if (Object.prototype.toString.call(spaces) == '[object Object]')
{ //spaces omitted -- shift arguments
options = spaces;
spaces = null;
}
else if (Object.prototype.toString.call(options) != '[object Object]')
options = {}; //options omitted -- default
spaces = spaces || 4;
//----- Set default options
options.keepNaN = options.keepNaN || false;
options.keepUndefined = options.keepUndefined || false;
options.keepRegExp = options.keepRegExp || true;
options.keepArrayKeys = options.keepArrayKeys || true;
options.keepFunctions = (options.keepFunctions || true) //requires...
/// && Function.getArguments && Function.getBody;
options.maxItemsPerLine = options.maxItemsPerLine || EZ.json.stringify.MAX_ITEMS_PER_LINE;
options.maxItemsLineLength = options.maxItemsLineLength || EZ.json.stringify.MAX_ITEMS_LINE_LENGTH;
//----- setup work varibles
var arrayLevel = 0,
skip = [], //do not extract / stringify keys
only = '', //only extract keys -- overrides only
padding = isNaN(spaces) //padding specifed by spaces with \n prefix
? spaces : '\n' + ' '.substr(0,spaces || ''),
//called for every node before EZjson_format()
nodeVisitor = typeof(replacer) != 'function' ? null : replacer;
if (Object.prototype.toString.call(replacer) === '[object Array]')
{
replacer.forEach(function(key) //for each specified key . . .
{
if (typeof(key) != 'string') return;
if (key.substr(0,1) == '-')
skip.push(key.substr(1)); //skip key if starts with dash
else
(only || []).push(key); //otherwise, add to only list
});
}
//------------------------------------------------------
var json = JSON.stringify(value, EZjson_format, spaces);
//------------------------------------------------------
if (json == undefined) return json;
//----- unescape EZjson_format() escape codes
json = json.replace(/("@@=@|@=@@"?)/g, ''); //remove outer quotes
json = json.replace(/@@~@@/g, '"'); //unescape inner quotes
json = json.replace(/\\n/g, '\n'); //convert \\n --> \n
json = json.replace(/@@#@@/g, '\\\\'); //unescape backslashes
json = json.replace(/@@EOL@@/g, '\n'); //... \n
json = json.replace(/@@@@/g, '\\n'); //... \\n
json = json.replace(/([{,]\s+)"([\w_]+?)":/gi, function(all, sep, key)
{ //un-quote Object keys
if ('null undefined'.indexOf(key) != -1) return all;
return sep + key + ":"
});
//==========
return json;
//==========
//______________________________________________________________________________
/**
* process Array, RegExp or multiline String
*/
function EZjson_format(key, value)
{
if (nodeVisitor) //TODO: not tested
{
value = nodeVisitor(value, EZjson_format, spaces);
}
var json = '';
if (value === null) return null;
//--------------------------\\
//----- format undefined -----\\
//------------------------------\\
if (value == undefined) //TODO: not complete
{
return options.keepUndefined ? undefined : null;
}
//--------------------\\
//----- format NaN -----\\
//------------------------\\
if (typeof(value) == 'number' && isNaN(value))
{ //TODO: not tested
return options.keepNaN ? NaN : null;
}
//---------------------------------\\
//----- format multiline String -----\\
//-------------------------------------\\
else if (typeof(value) == 'string' && value.includes('\n'))
{ //TODO: check option
return '@@EOL@@' + value.replace(/\n/g, '@@@@@@EOL@@');
}
//---------------=--------------------\\
//----- convert function to Object -----\\
//----------------------------------------\\
else if (typeof(value) == 'function')
{
var obj = {};
// keep function definition properties if option specified
if (options.keepFunctions)
{
var pattern = /function\s*(\w*)\s*\(([\s\S]*?)\)[^{]*{\s*([\s\S]*)}/;
var results = value.toString().match(pattern);
obj.function = {
name: results[1] || '',
arguments: (results[2].length ? results[2].split(',') : []),
body: results[3].trim().split('\n'),
_constructorName: value.constructor.name
}
}
// always keep function properties
Object.keys(value).forEach(function(key)
{ obj[key] = value[key]; });
return obj;
}
//--------------=------------------\\
//----- no change if not Object -----\\
//------------------------------------\\
else if (typeof(value) != 'object')
{
return value;
}
//--------------------------------\\
//----- format json for RegExp -----\\
//------------------------------------\\
else if (value.constructor == RegExp)
{
if (!options.keepRegExp) return value;
var clone = {_constructorName: value.constructor.name};
Object.getOwnPropertyNames(value).forEach(function(key)
{ clone[key] = escapeChar(value[key]) });
return clone;
}
//--------------------------------\\
//----- no change if not Array -----\\
//------------------------------------\\
else if (value.constructor != Array)
return value;
//--------------------------------\\
//----- format json for Array -----\\
//------------------------------------\\
else
{
arrayLevel++;
//----- Create new Object() for any non-numeric enumerable Array keys.
// If any found, clone Array and push new Object() onto the cloned
// Array as pseudo item that will subequently stringify into json.
var properties = {_____keys_____: 0};
if (Object.keys(value).join('').replace(/\d*/g,''))
{
Object.keys(value).forEach(function(key)
{
if (!value.hasOwnProperty(key)) return;
if (skip.indexOf(key) != -1) return;
if (only && only.indexOf(key) != -1) return;
if (isNaN(key) || parseInt(key) >= value.length)
{
properties._____keys_____++;
properties[key] = value[key];
}
});
if (properties._____keys_____) //named Array keys found
{
value = value.slice();
value.push(properties);
}
}
//----- stringify Array items including pseudo item added above
var delim = '';
var itemCount = 0;
var isMultiline = false;
var jsonForLine = '';
for (var idx=0; idx<value.length; idx++)
{ //item json -- remove outer quotes
var jsonForItem = JSON.stringify(value[idx], EZjson_format, spaces);
jsonForItem = jsonForItem.replace(/(^"@@=@|@=@@"$)/g, '');
var useSepLine = false;
jsonForLine += delim + jsonForItem;
if (typeof(value[idx]) == 'string'
&& jsonForItem.indexOf('@@EOL@@') != -1)
{
useSepLine = true; //multiline String
json += delim
delim = '';
}
if (typeof(value[idx]) == 'object' && value[idx] != null)
useSepLine = true; //separate line for Object json
else if (options.maxItemsLineLength && jsonForLine.length > options.maxItemsLineLength)
useSepLine = true; //separate line for long json String
else if ((options.maxItemsPerLine && itemCount >= options.maxItemsPerLine)
|| (options.maxItemsLineLength && (jsonForLine+jsonForItem).length > options.maxItemsLineLength))
{ //start newline after too many items
json += delim.replace(/ /, '\n')
delim = '';
itemCount = 0;
jsonForLine = jsonForItem;
isMultiline = true;
}
if (useSepLine)
{
json += delim.replace(/ /, '\n')
+ jsonForItem
+ (idx < (value.length - 1) ? ',\n' : '');
delim = '';
itemCount = 0;
isMultiline = true;
jsonForLine = '';
}
else
{ //append to current line
json += delim + jsonForItem;
delim = ', ';
itemCount++;
}
}
//----- wrap json with [...] and indent as needed
var endPadding = '';
if (isMultiline) //when isMultiline, indent ITEMS
{
json = padding + json.replace(/\n/g, padding);
if (arrayLevel > 1) //indent more if nested Array
json = json.replace(/\n/g, padding) + padding;
else if (key)
endPadding = padding;
else
endPadding = '\n';
}
if (key) //not top level, indent entire ARRAY
json = json.replace(/\n/g, padding);
json = '[' + json + endPadding + ']';
arrayLevel--;
}
//---------------------------------------\\
//----- return escaped json for value -----\\
//-------------------------------------------\\
json = '@@=@' + json + '@=@@'; //wrap json with prefix/suffix escape codes...
return escapeChar(json); //...to discard outer quotes added upon return
}
/**
*
*/
function escapeChar(json)
{
if (typeof(json) != 'string') return json;
json = json.replace(/\n/g, '@@EOL@@'); //escape embedded newlines
json = json.replace(/"/g, '@@~@@'); //...quotes
json = json.replace(/\\/g, '@@#@@'); //...backslashes
return json;
}
}
EZ.json.stringify.MAX_ITEMS_PER_LINE = 10;
EZ.json.stringify.MAX_ITEMS_LINE_LENGTH = 80;
//_____________________________________________________________________________________________
EZ.stringify = EZ.json.stringify; //test framework does not support nested function names
EZ.stringify.test = function()
{
// shared data
var ex = 'na';
var note = '';
var obj, json, regex;
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
// #1
ex = '[\n'
+ ' "score", "offsets",\n'
+ ' {\n'
+ ' _____keys_____: 2,\n'
+ ' score: true,\n'
+ ' scoredKey: true\n'
+ ' }\n'
+ ']'
note = 'ObjectLike Array with'
+ 'named keys'
EZ.test.run(EZ.global.testdata.include, 4, {EZ: {ex:ex, note:note}})
//_______________________________________________________________________________
// #2
ex = JSON.stringify(EZ.global.testdata.person, null, 4); format()
note = 'Object same as native\n'
+ 'except keys not quoted'
EZ.test.run(EZ.global.testdata.person, 4, {EZ: {ex:ex, note:note}})
//_______________________________________________________________________________
// #3
ex = JSON.stringify(EZ.global.testdata.array);
ex = ex.replace(/,/g, ', '); note = 'Pure Array -- no item '
+ 'contains an object so: '
+ 'Array is not indented '
+ 'but space after comma'
EZ.test.run(EZ.global.testdata.array, {EZ: {ex:ex, note:note}})
//_______________________________________________________________________________
// #4
ex = JSON.stringify(EZ.global.testdata.arraySparse); format();
//ex = ex.replace(/null/, /undefined/)
note = 'Array sparely poulated '
+ 'item[2] undefined but '
+ 'native stringify treats '
+ 'as null'
EZ.test.run(EZ.global.testdata.arraySparse, {EZ: {ex:ex, note:note}})
//_______________________________________________________________________________
// #5
ex = JSON.stringify(EZ.global.testdata.personArrayLike, null, 4); format();
note = 'ArrayLike Object: same '
+ 'as native stringify '
+ 'except: keys not quoted '
EZ.test.run(EZ.global.testdata.personArrayLike, {EZ: {ex:ex, note:note}})
//_______________________________________________________________________________
// #6
ex = JSON.stringify('', null, 4); note = 'empty string exactly '
+ 'as native stringify '
EZ.test.run('', {EZ: {ex:'""', note:note}})
//_______________________________________________________________________________
// #7
ex = JSON.stringify('', null, 4); note = 'null exactly same '
+ 'as native stringify '
EZ.test.run(null, {EZ: {ex:'null', note:note}})
//_______________________________________________________________________________
// #8
json = JSON.stringify(EZ.global.testdata.objectLike).replace(/,/g, ', ')
// [1,2,null,null,null,"five"]
json = json.replace(/\[/g, '[\n ').replace(/]/, ',\n {\n '
+ '_____keys_____: 1,\n ');
ex = 'person: ' + JSON.stringify(EZ.global.testdata.person, null, 4); format();
ex = json + ex.replace(/\n/g, '\n ') + '\n }\n]';
note = 'ObjectLike Array has\n'
+ 'named keys - IGNORED '
+ 'by native stringify'
EZ.test.run(EZ.global.testdata.objectLike, {EZ: {ex:ex, note:note}})
//_______________________________________________________________________________
// #9
var a = EZ.global.testdata.array.slice();
a.push(EZ.global.testdata.person, true, false, 'xyz')
ex = JSON.stringify(a, null, 4); format();
ex = ex.replace(/1,[\s\S]*?2,/, '1, 2,')
ex = ex.replace(/true,[\s\S]*?"/, function(all) {return all.replace(/,\n\s*/g, ', ') })
note = 'Array format same as native when ANY array item contains object '
+ 'except: keys unquoted and spaces after Array item commas'
EZ.test.run(a, {EZ: {ex:ex, note:note}})
//_______________________________________________________________________________
// #10
ex = JSON.stringify(EZ.global.testdata.fuse,null,4); format();
json = '\n {\n _____keys_____: 2,'
for (key in EZ.global.testdata.fuse.include)
{ // append options.include Array named keys
if (EZ.global.testdata.fuse.include.hasOwnProperty(key) && isNaN(key))
json += '\n ' + key + ': ' + EZ.global.testdata.fuse.include[key] + ',';
}
ex = ex.replace(/],/, ',' + json.clip() + '\n }\n ],');
ex = ex.replace(/\[/, '[\n ');
note = 'Object with embedded ObjectLike include Array with named keys'
EZ.test.run(EZ.global.testdata.fuse, {EZ: {ex:ex,note:note}})
//______________________________________________________________________________
// #11
ex = JSON.stringify(EZ.global.testdata.arraySparsePlus, null, 4); format();
ex = ex.replace(/(\[\s*)([\s\S]*?)(?=]|,\s*\{)/gi,
function(all,bracket,items)
{
return bracket + items.replace(/,\s*/g, ', ');
});
ex = ex.replace(/\s\[\s*"O([^\]]*?)\s+\]/gi, '\n ["O$1]')
ex = ex.replace(/\[\s*"J([^{]*?)\s*\]/g, '["J$1]'.replace(/\s+/g, ' '))
note = 'complex Array with '
+ 'no ObjectLike Arrays '
EZ.test.run(EZ.global.testdata.arraySparsePlus, {EZ: {ex:ex, note:note}})
//_______________________________________________________________________________
// #12
ex = JSON.stringify(EZ.global.testdata.objectLikeMore.person, null, 4); format();
json = ex.replace(/\n/g, '\n ')
json = '{\n'
+ ' _____keys_____: 1,\n'
+ ' person: ' + json + '\n'
+ '}'
json = ' ' + json.replace(/\n/g, '\n ');
ex = JSON.stringify(EZ.global.testdata.objectLikeMore,null,4); format();
ex = ex.replace(/(\[\s*)([\s\S]*?)(?=]|,\s*\{)/gi,
function(all,bracket,items)
{
return bracket + items.replace(/,\s*/g, ', ');
});
ex = ex.replace(/(2,) /, '$1');
ex = ex.replace(/( ])/, '$1,\n' + json);
json = '"score", "offsets",\n'
+ '{\n'
+ ' _____keys_____: 2,\n'
+ ' score: true,\n'
+ ' scoredKey: true\n'
+ '}';
json = json.replace(/\n/g, '\n ');
ex = ex.replace(/\[\s*"score"[\s\S]*?"offsets"/,'\n [\n ' + json);
note = 'complex ObjectLike'
EZ.test.run(EZ.global.testdata.objectLikeMore, {EZ: {ex:ex, note:note}})
//_______________________________________________________________________________
// #13
obj = cloneObject(EZ.global.testdata.regex);
ex = JSON.stringify(obj,null,4); format();
note = 'RegExp Standalone'
EZ.test.run(EZ.global.testdata.regex, {EZ: {ex:ex, note:note}})
//_______________________________________________________________________________
// #14
obj = [cloneObject(EZ.global.testdata.regex)];
ex = JSON.stringify(obj,null,4); format();
note = 'RegExp in Array'
EZ.test.run([EZ.global.testdata.regex], {EZ: {ex:ex, note:note}})
//_______________________________________________________________________________
// #15
obj = {regex: cloneObject(EZ.global.testdata.regex)};
ex = JSON.stringify(obj,null,4); format();
note = 'RegExp in Object'
EZ.test.run({regex: EZ.global.testdata.regex}, {EZ: {ex:ex, note:note}})
//_______________________________________________________________________________
// #16
var manyItems = [0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9]
ex = '[\n 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,\n 0, 1, 2, 3, 4, 5, 6, 7, 8, 9\n]'
note = '20 items'
EZ.test.run(manyItems, {EZ: {ex:ex, note:note}})
//_______________________________________________________________________________
// #17
ex = JSON.stringify(EZ.global.testdata.multiline, null, 4); format();
ex = ex.replace(/1,[\s\S]*"John/, '1, "a", "\nJohn');
ex = ex.replace(/\\n/g, '\\n\n');
ex = ex.replace(/"x[\s\S]*?z"/, '"x", "y", "z"');
note = 'multiline String'
EZ.test.run(EZ.global.testdata.multiline, {EZ: {ex:ex, note:note}})
//_______________________________________________________________________________
// #18
ex = ''
note = 'function'
EZ.test.run(EZ.testSample, {EZ: {ex:ex, note:note}})
//_______________________________________________________________________________
// #19
ex = ''
note = 'function'
EZ.test.run(EZ.testSample, {EZ: {ex:ex, note:note}})
//_______________________________________________________________________________
//...............................................................................
/**
* Internal test helper function
* convert most native stringify to EZ.stringify
*/
function format()
{
//ex = ex.replace(/"(\w*?)":/gi,'$1:'); //un-quote keys
ex = ex.replace(/([{,]\s+)"([\w_]+?)":/gi, function(all, sep, key)
{
if ('null undefined'.indexOf(key) != -1) return all;
return sep + key + ":"
});