-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathish.js
3697 lines (3286 loc) · 207 KB
/
ish.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
//################################################################################################
/** @file Q: Are you using Vanilla Javascript?<br/>A: ...ish
* <div style="font-size: 75%; margin-top: 20px;">
* JSish => `Zero-dependency OOP-organized Javascript code snippets, including:
* <ul>
* <li>Type-safety and type-casting - assisting developers in overcoming issues related to loose typing via Vanilla Javascript (rather than syntactic sugar à la TypeScript);</li>
* <li>OOP features - partial class definitions with shared private members and multiple inheritance;</li>
* <li>Strong typing of function signatures along with support for dynamic polymorphism/function overloading;</li>
* <li>Dependency injection;</li>
* <li>Object traversal, extension and querying features;</li>
* <li>Custom events;</li>
* <li>Data interpolation - CSV, XML, Punycode and POJO parsing;</li>
* <li>Additional Types - Enumerations, UUID;</li>
* <li>Large/small number support;</li>
* <li>Support back to IE8, with most features supported back to IE6;</li>
* <li>Growing unit test coverage with <code><a href="https://www.chaijs.com/api/assert/" target="_new">Chai.Assert</a></code>;</li>
* <li>Isomorphic - client- and server-side code in one codebase.</li>
* </ul>
* with all non-UI features available both client-side (in-browser) and server-side (Node/etc.).
* <p style="margin-top: 20px;">
* All features are organized in individually includable mixins organized by namespace/major features with only the core <code>ish.js</code> functionality required to bootstrap.
* </p>`
* </div>
* @version 0.14.2024-02-03
* @author Nick Campbell
* @license MIT
* @copyright 2014-2024, Nick Campbell
*/ /**
* ish.js's (renameable) global object.
* @namespace ish
*/ //############################################################################################
/*global module, define, global, require, process, __dirname*/ //# Enable Node globals for JSHint
/*jshint maxcomplexity:9 */ //# Enable max complexity warnings for JSHint
(function (/*global, module, require, process, __dirname*/) {
'use strict';
var _Object_prototype_toString = Object.prototype.toString, //# code-golf
bServerside = (function () { //# Are we running under nodeJS (or possibly have been required as a CommonJS module), SEE: https://stackoverflow.com/questions/4224606/how-to-check-whether-a-script-is-running-under-node-js
try { return (process && _Object_prototype_toString.call(process) === '[object process]'); }
catch (e) { return false; }
})(),
_root = (bServerside ? global : window), //# code-golf
_document = (bServerside ? {} : document), //# code-golf
_undefined /*= undefined*/, //# code-golf
_null = null, //# code-golf
oPrivate = {},
oTypeIsIsh = { //# Set the .ver and .target under .type.is.ish (done here so it's at the top of the file for easy editing) then stub out the .app and .lib with a new .pub oInterfaces for each
config: {
ver: '0.14.2024-02-03',
onServer: bServerside,
debug: true,
//script: _undefined,
target: "ish",
plugins: {
//import: [],
//path: "", // _document.currentScript.src,
//cache: false,
//importedBy: ""
},
typeOrder: [
'bool',
'int', 'float', /*'numeric',*/
'date', 'str',
'fn', 'dom', 'arr', /*'collection',*/ 'obj',
'symbol'
]
},
public: {
//is: function () {},
//import: function () {},
expectedErrorHandler: function expectedErrorHandler(/*e*/) {}
}
},
oInterfaces = {
pub: function () {
return {
data: {},
//options: {},
ui: {}
};
}
}, //# oInterfaces
core = {
//config: function (oConfig) { return function () {}; },
//resolve: function () {},
//extend: function () {},
//require: function () {},
//type: {},
//oop: {},
//io: {},
//ui: {},
//app: oInterfaces.pub(),
//lib: oInterfaces.pub() //# + sync
}
;
//# Null function used as a placeholder when a valid function reference is required
function noop() {} //# noop
//################################################################################################
/** Collection of Type-based functionality (<code>is</code> and <code>mk</code> only)
* @namespace ish.type
*/ //############################################################################################
core.type = function () {
//# Thanks to Symbol()s not wanting to be casted to strings or numbers (i.e. parseFloat, regexp.test, new Date), we need to wrap the test below for the benefit of ish.type()
function mkStr(s) {
try {
s = (s + "");
} catch (e) {
s = "";
}
return s;
}
//#########
/** Determines the type of the passed value.
* @function ish.type.!
* @param {variant} x Value to interrogate.
* @param {variant[]} [a_vOrder=ish.config.ish().typeOrder] Type ordering to use during interrogation.
* @returns {function} Value indicating the type of the passed value.
* @todo Detail recognized a_vOrder values
*/ //#####
function type(x, a_vOrder) {
var fnCurrent, vCurrent, i,
fnReturnVal /* = _undefined */
;
//# Ensure the passed a_vOrder is an array, defaulting to our .typeOrder if none was passed
a_vOrder = core.type.arr.mk(a_vOrder, core.config.ish().typeOrder);
//# If we have a a_vOrder to traverse, do so now calculating each fnCurrent as we go
//# NOTE: We avoid using core.type.fn.* below to keep the code requirements to just that which is defined herein
if (core.type.arr.is(a_vOrder, true)) {
for (i = 0; i < a_vOrder.length; i++) {
//# Try to .resolve the current a_vOrder from core.type.*||core.type.is.*, else .mk it a .fn (defaulting to .noop on failure)
//# NOTE: We avoid using core.resolve below to keep the code requirements to just that which is defined herein
vCurrent = a_vOrder[i];
fnCurrent = (
(core.type[vCurrent] || {}).is ||
core.type.is[vCurrent] ||
core.type.fn.mk(vCurrent)
);
//# If the passed x returns true from the fnCurrent (indicating that it's of that type), reset our fnReturnVal and fall form the loop
//# NOTE: If fnCurrent is set to .noop above, it return nothing/undefined which is interpreted as false below
if (fnCurrent(x)) {
fnReturnVal = fnCurrent;
break;
}
}
}
return fnReturnVal;
} //# ish.type
//#########
/** Determines if the passed value is an instance of the referenced type.
* @namespace ish.type.is
*/ /**
* Determines if the passed value is an instance of the passed type.
* @function ish.type.is.!
* @param {variant} x Value to interrogate.
* @param {variant} t Type to use during interrogation.
* @returns {boolean} Value representing if the passed value is an instance of the passed type.
*/ //#####
type.is = function isType(x, t) {
try {
return (x instanceof t);
} catch (e) {
return false;
}
}; //# ish.type.is
//#########
/** Determines if the passed value is a native Javascript function or object.
* @function ish.type.is.native
* @param {variant} x Value to interrogate.
* @returns {boolean} Value representing if the passed value is a native Javascript function or object.
* @see {@link http://davidwalsh.name/essential-javascript-functions|DavidWalsh.name}
*/ //#####
type.is.native = function () {
var toString = Object.prototype.toString, // Used to resolve the internal `[[Class]]` of values
fnToString = Function.prototype.toString, // Used to resolve the decompiled source of functions
reHostCtor = /^\[object .+?Constructor\]$/, // Used to detect host constructors (Safari > 4; really typed array specific)
reNative = RegExp('^' + // Compile a regexp using a common native method as a template. We chose `Object#toString` because there's a good chance it is not being mucked with.
String(toString) // Coerce `Object#toString` to a string
.replace(/[.*+?^${}()|[\]/\\]/g, '\\$&') // Escape any special regexp characters
.replace(/toString|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') +
'$' // Replace mentions of `toString` with `.*?` to keep the template generic. Replace thing like `for ...` to support environments like Rhino which add extra info such as method arity.
)
;
return function isNative(x) {
var _type = typeof x;
return _type == 'function' ?
reNative.test(fnToString.call(x)) : // Use `Function#toString` to bypass x's own `toString` method and avoid being faked out.
(x && _type == 'object' && reHostCtor.test(toString.call(x))) || // Fallback to a host object check because some environments will represent things like typed arrays as DOM methods which may not conform to the normal native pattern.
false
;
};
/*native: function () {
var toString = Object.prototype.toString, // Used to resolve the internal `[[Class]]` of x
fnToString = Function.prototype.toString, // Used to resolve the decompiled source of functions
reHostCtor = /^\[object .+?Constructor\]$/, // Used to detect host constructors (Safari > 4; really typed array specific)
reNative = RegExp('^' + // Compile a regexp using a common native method as a template. We chose `Object#toString` because there's a good chance it is not being mucked with.
String(toString) // Coerce `Object#toString` to a string
.replace(/[.*+?^${}()|[\]\/\\]/g, '\\$&') // Escape any special regexp characters
// Replace mentions of `toString` with `.*?` to keep the template generic.
// Replace thing like `for ...` to support environments like Rhino which add extra info such as method arity.
.replace(/toString|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') +
'$'
)
;
return function (x) {
var type = typeof x;
return x == 'function' ?
reNative.test(fnToString.call(x)) : // Use `Function#toString` to bypass the x's own `toString` method and avoid being faked out.
// Fallback to a host object check because some environments will represent things like typed arrays as DOM methods which may not conform to the normal native pattern.
(x && type == 'object' && reHostCtor.test(toString.call(x))) || false
;
}
}(), //# ish.type.is.native*/
}(); //# ishtype.is.native
//#########
/** Determines if the passed value is a list type (e.g. HTMLCollection|HTMLFormControlsCollection|HTMLOptionsCollection|NodeList|NamedNodeMap|Arguments + Object to support <IE9).
* @function ish.type.is.collection
* @param {variant} x Value to interrogate.
* @param {object|boolean} [vOptions=false] Value representing if empty collections are to be ignored or the desired options:
* @param {boolean} [vOptions.disallow0Length=false] Value representing if empty collections are to be ignored.
* @param {boolean} [vOptions.allowObject=false] Value representing if Objects are to be included in the test (to support <IE9).
* @param {boolean} [vOptions.allowArray=false] Value representing if Arrays are to be included in the test.
* @returns {boolean} Value representing if the passed value is a collection type.
*/ //#####
type.is.collection = function isCollection(x, vOptions) {
var oOptions = core.type.obj.mk(vOptions),
bDisallow0Length = (vOptions === true || oOptions.disallow0Length)
;
return (
(oOptions.allowObject && core.type.obj.is(x, { nonEmpty: bDisallow0Length })) ||
(oOptions.allowArray && core.type.arr.is(x, bDisallow0Length)) ||
(
(x && core.type.is.numeric(x.length) && (!bDisallow0Length || x.length > 0)) &&
/^\[object (HTMLCollection|HTMLFormControlsCollection|HTMLOptionsCollection|NodeList|NamedNodeMap|Arguments)\]$/.test(Object.prototype.toString.call(x))
)
);
}; //# ish.type.is.collection
//#########
/** Determines if the passed value is a numeric value (includes implicit casting per the Javascript rules, see: {@link: ish.type.int.mk}).
* @function ish.type.is.numeric
* @param {variant} x Value to interrogate.
* @returns {boolean} Value representing if the passed value is a numeric type.
*/ //#####
type.is.numeric = function isNumeric(x) {
var reNumber = /^[-0-9]?[0-9]*(\.[0-9]{1,})?$/, // (bAllowCommaDecimal === true ? /^[-0-9]?[0-9]*([\.\,][0-9]{1,})?$/ : /^[-0-9]?[0-9]*(\.[0-9]{1,})?$/),
bReturnVal = false
;
//# Thanks to Symbol()s not wanting to be casted to strings or numbers (i.e. parseFloat, regexp.test, new Date), we need to wrap the test below for the benefit of ish.type()
try {
bReturnVal = (
reNumber.test(x) &&
!isNaN(parseFloat(x)) &&
isFinite(x)
);
} catch (e) {}
return bReturnVal;
}; //# ish.type.is.numeric
//#########
/** Determines if the passed value is an instance of ish.js.
* @function ish.type.is.ish
* @param {variant} x Value to interrogate.
* @returns {boolean} Value representing if the passed value is an instance of ish.js.
*/ //#####
type.is.ish = function isIsh(x) {
return (arguments.length === 0 || x === core);
}; //# ish.type.is.ish
//####
//####
//#########
/** Boolean-based type functionality.
* @namespace ish.type.bool
*/ //#####
type.bool = {
//#########
/** Determines if the passed value represents a boolean.
* @function ish.type.bool.is
* @param {variant} x Value to interrogate.
* @param {boolean} [bAllowString=false] Value representing if strings are to be considered valid.
* @returns {boolean} Value representing if the passed value represents a boolean.
*/ //#####
is: function isBool(x, bAllowString) {
var sB = mkStr(x).toLowerCase().trim();
return !!(
_Object_prototype_toString.call(x) === '[object Boolean]' ||
(bAllowString && (sB === "true" || sB === "false"))
);
}, //# bool.is
//#########
/** Casts the passed value into a boolean.
* @function ish.type.bool.mk
* @param {variant} x Value to interrogate.
* @param {variant} [vDefaultVal=truthy_value_of_x] Value representing the default return value if casting fails.
* @returns {boolean} Value representing the passed value as a boolean type.
*/ //#####
mk: function (x, vDefaultVal) {
var bReturnVal = (
arguments.length > 1 ?
vDefaultVal : (
x ? true : false
)
);
//# Since the bReturnVal was defaulted to the vDefaultVal above, pull it's value back into our vDefaultVal
vDefaultVal = bReturnVal;
//#
if (core.type.bool.is(x)) {
bReturnVal = x;
}
//#
else if (x == 0 || x == 1) {
bReturnVal = !!core.type.int.mk(x);
}
//#
else if (core.type.str.is(x, true)) {
x = x.trim().toLowerCase();
bReturnVal = (x === 'true' || (
x === 'false' ? false : vDefaultVal
));
}
return bReturnVal;
} //# bool.mk
}; //# ish.type.bool
//#########
/** Integer-based type functionality.
* @namespace ish.type.int
*/ //#####
type.int = {
//#########
/** Determines if the passed value represents an integer (includes implicit casting per the Javascript rules, see: {@link: ish.type.int.mk}).
* @function ish.type.int.is
* @param {variant} x Value to interrogate.
* @returns {boolean} Value representing if the passed value represents an integer.
*/ //#####
is: function isInt(x) {
var fX = core.type.float.mk(x);
return (core.type.is.numeric(x) && fX % 1 === 0);
}, //# int.is
//#########
/** Casts the passed value into an integer (includes implicit casting per the Javascript rules, see below).
* @function ish.type.int.mk
* @param {variant} x Value to interrogate.
* @param {variant} [vDefaultVal=0] Value representing the default return value if casting fails.
* @param {integer} [iRadix=10] Value between 2-36 that represents the radix (the base in mathematical numeral systems) passed into <code>parseInt</code>.
* @returns {integer} Value representing the passed value as an integer type.
* @example
* <caption>
* Javascript has some funky rules when it comes to casting numeric values, and they are at play in this function.
* <br/>In short, the first non-whitespace numeric characters are used in the cast, until any non-numeric character is hit.
* </caption>
* "12 monkeys!" === 12;
* " 12 monkeys!" === 12;
* "12monkeys!" === 12;
* "1.2 monkeys!" === 1.2;
* "1,2 monkeys!" === 1; // (not 1.2, sorry Europe)
* "1 2 monkeys!" === 1; // (not 12)
* "1,200 monkeys!" === 1; // (not 1200)
* "11 - there were 12 monkeys!" === 11;
* "twelve (12) monkeys!" === undefined;
* "$12 monkeys!" === undefined;
*/ //#####
mk: function (x, vDefaultVal, iRadix) {
var iReturnVal = parseInt(x, (iRadix > 1 && iRadix < 37 ? iRadix : 10));
return (!isNaN(iReturnVal) ?
iReturnVal :
(arguments.length > 1 ? vDefaultVal : 0)
);
} //# int.mk
}; //# ish.type.int
//#########
/** Floating Point Number-based type functionality.
* @namespace ish.type.float
*/ //#####
type.float = {
//#########
/** Determines if the passed value represents a floating point number (includes implicit casting per the Javascript rules, see: {@link: ish.type.int.mk}).
* @function ish.type.float.is
* @param {variant} x Value to interrogate.
* @returns {boolean} Value representing if the passed value represents a floating point number.
*/ //#####
is: function isFloat(x) {
var fX = core.type.float.mk(x);
return (core.type.is.numeric(x) && fX % 1 !== 0);
}, //# float.is
//#########
/** Casts the passed value into a floating point number (includes implicit casting per the Javascript rules, see: {@link: ish.type.int.mk}).
* @function ish.type.float.mk
* @param {variant} x Value to interrogate.
* @param {variant} [vDefaultVal=0] Value representing the default return value if casting fails.
* @param {integer} [iRadix=10] Value between 2-36 that represents the radix (the base in mathematical numeral systems) passed into <code>parseFloat</code>.
* @returns {float} Value representing the passed value as an floating point number type.
*/ //#####
mk: function (x, vDefaultVal, iRadix) {
var fReturnVal;
//# Thanks to Symbol()s not wanting to be casted to strings or numbers (i.e. parseFloat, regexp.test, new Date), we need to wrap the test below for the benefit of ish.type()
try {
fReturnVal = parseFloat(x, (iRadix > 1 && iRadix < 37 ? iRadix : 10));
} catch (e) {}
return (!isNaN(fReturnVal) ?
fReturnVal :
(arguments.length > 1 ? vDefaultVal : 0)
);
} //# float.mk
}; //# ish.type.float
//#########
/** Date-based type functionality.
* @namespace ish.type.date
*/ //#####
type.date = function () {
//#
function mkDate(d, vOptions) {
var bIsDate = _Object_prototype_toString.call(d) === "[object Date]";
//# Ensure the passed vOptions is an .obj
vOptions = core.type.obj.mk(vOptions, { allowNumeric: vOptions === true });
//# If the passed d(ate) isn't an [object Date] and we've not been told to be .strict
if (!bIsDate && !vOptions.strict) {
//# If the passed d(ate) .is.numeric, parse it as a float (to allow for the widest values) and reset bIsDate
//# NOTE: We have to do this before .is .str as "0" will resolve to a string
if (vOptions.allowNumeric && core.type.is.numeric(d)) {
d = new Date(parseFloat(d));
bIsDate = !isNaN(d.valueOf());
}
//# Else if the passed d(ate) .is .str, try throwing it at new Date() and reset bIsDate
//# NOTE: `new Date("32")` in Chrome return a 2032-based date while `new Date(32)` returns 1970-1-1 + 32ms, hence the exclusion of .is.numeric strings
else if (core.type.str.is(d) && !core.type.is.numeric(d)) {
d = new Date(d);
bIsDate = !isNaN(d.valueOf());
}
}
return {
b: bIsDate,
d: d
};
} //# mkDate
return {
//#########
/** Determines if the passed value represents a date.
* @function ish.type.date.is
* @param {variant} x Value to interrogate.
* @param {boolean|object} [vOptions] Value representing if numeric values are to be ignored or the following options:
* @param {boolean} [vOptions.allowNumeric=false] Value representing if numeric values are to be ignored.
* @param {boolean} [vOptions.strict=false] Value representing if only <code>[object Date]</code> are to be allowed.
* @returns {boolean} Value representing if the passed value represents a date.
*/ //#####
is: function isDate(x, vOptions) {
return mkDate(x, vOptions).b;
}, //# date.is
//#########
/** Casts the passed value into a date.
* @function ish.type.date.mk
* @param {variant} x Value to interrogate.
* @param {variant} [vDefaultVal=new Date()] Value representing the default return value if casting fails.
* @returns {Date} Value representing the passed value as a date type.
*/ //#####
mk: function (x, vDefaultVal) {
var oResult = mkDate(x, true);
return (oResult.b ?
oResult.d :
(arguments.length > 1 ? vDefaultVal : new Date())
);
} //# date.mk
};
}(); //# ish.type.date
//#########
/** String-based type functionality.
* @namespace ish.type.str
*/ //#####
type.str = {
//#########
/** Determines if the passed value represents a string.
* @function ish.type.str.is
* @param {variant} x Value to interrogate.
* @param {boolean} [bDisallowNullString=false] Value representing if null-strings (e.g. "") are to be disallowed.
* @param {boolean} [bTrimWhitespace=false] Value representing if leading and trailing whitespace is to be trimmed prior to integration.
* @returns {boolean} Value representing if the passed value represents a string.
*/ //#####
is: function isStr(x, bDisallowNullString, bTrimWhitespace) {
return (
(typeof x === 'string' || x instanceof String) &&
(!bDisallowNullString || x !== "") &&
(!bTrimWhitespace || mkStr(x).trim() !== "")
);
}, //# str.is
//#########
/** Casts the passed value into a string.
* @function ish.type.str.mk
* @param {variant} x Value to interrogate.
* @param {variant} [vDefaultVal=""] Value representing the default return value if casting fails.
* @returns {string} Value representing the passed value as a string type.
*/ //#####
mk: function (x, vDefaultVal) {
var sS = (core.type.obj.is(x, { strict: true }) ? JSON.stringify(x) : mkStr(x));
return ((x || x === false || x === 0) && sS ?
sS :
(arguments.length > 1 ? vDefaultVal : "")
);
} //# str.mk
}; //# ish.type.str
//#########
/** Function-based type functionality.
* @namespace ish.type.fn
*/ //#####
type.fn = {
//#########
/** Determines if the passed value represents a function.
* @function ish.type.fn.is
* @param {variant} x Value to interrogate.
* @returns {boolean} Value representing if the passed value represents a function.
* @see {@link https://davidwalsh.name/javascript-detect-async-function|DavidWalsh.name}
*/ //#####
is: function isFn(x) {
return (
_Object_prototype_toString.call(x) === '[object Function]' ||
(x && x.constructor && x.constructor.name === "AsyncFunction")
);
}, //# fn.is
//#########
/** Casts the passed value into a function.
* @function ish.type.fn.mk
* @param {variant} x Value to interrogate.
* @param {variant} [vDefaultVal=ish.type.fn.noop] Value representing the default return value if casting fails.
* @returns {function} Value representing the passed value as a function type.
*/ //#####
mk: function (x, vDefaultVal) {
var vResolved,
fnResolve = core.resolve || function (_passedRoot, sKey) { return _passedRoot[sKey]; },
fnReturnVal = (arguments.length > 1 ? vDefaultVal : noop)
;
//# If the passed x .is a .fn, reset our fnReturnVal to it
if (core.type.fn.is(x)) {
fnReturnVal = x;
}
//# Else we need to see if f can be vResolved
else {
vResolved = (core.type.str.is(x) || core.type.arr.is(x) ? fnResolve(_root, x) : _undefined);
//# If the passed f .is a .str or .arr and we vResolved it to a .fn, reset our fnReturnVal to it
if (core.type.fn.is(vResolved)) {
fnReturnVal = vResolved;
}
}
return fnReturnVal;
} //# fn.mk
}; //# ish.type.fn
//#########
/** Array-based type functionality.
* @namespace ish.type.arr
*/ //#####
type.arr = {
//#########
/** Determines if the passed value represents an array.
* @function ish.type.arr.is
* @param {variant} x Value to interrogate.
* @param {boolean} [bDisallow0Length=false] Value representing if zero length arrays are to be ignored.
* @returns {boolean} Value representing if the passed value represents an array.
*/ //#####
is: function isArr(x, bDisallow0Length) {
return (_Object_prototype_toString.call(x) === '[object Array]' &&
(!bDisallow0Length || x.length > 0)
);
}, //# arr.is
//#########
/** Casts the passed value into an array.
* @function ish.type.arr.mk
* @param {variant} x Value to interrogate.
* @param {variant} [vDefaultVal=[]] Value representing the default return value if casting fails.
* @returns {variant[]} Value representing the passed value as an array type.
*/ //#####
mk: function (x, vDefaultVal) {
//# Preconvert a .collection reference into an array
x = (core.type.is.collection(x) ? Array.prototype.slice.call(x) : x);
return (core.type.arr.is(x) ?
x :
(arguments.length > 1 ? vDefaultVal : [])
);
} //# arr.mk
}; //# ish.type.arr
//#########
/** Object-based type functionality.
* @namespace ish.type.obj
*/ //#####
type.obj = function () {
//#
function mkJSON(v) {
try {
return JSON.parse(core.type.str.mk(v).replaceAll("\n", "\\n"));
} catch (e) {/*oTypeIsIsh.public.expectedErrorHandler(e);*/}
} //# mkJSON
//#
function objBase(v, bAllowFn, bAllowJSON, bStrict) {
var bReturnVal = !!(
v && v === Object(v) && (bAllowFn || !core.type.fn.is(v)) &&
(!bStrict || _Object_prototype_toString.call(v) === '[object Object]')
);
//# If we failed the test above, we are bAllow(ing)JSON and the passed v(ariant) .is .str
if (!bReturnVal && bAllowJSON && core.type.str.is(v, true)) {
//# .mkJSON the passed v(ariant), resetting our bReturnVal based on it's success
v = mkJSON(v);
bReturnVal = !!(v);
}
return {
b: bReturnVal,
o: v
};
} //# objBase
return {
//#########
/** Determines if the passed value represents an object.
* @function ish.type.obj.is
* @param {variant} x Value to interrogate.
* @param {boolean|object} [vOptions] Value representing if empty objects are to be ignored or the following options:
* @param {boolean} [vOptions.nonEmpty=false] Value representing if empty objects are to be ignored.
* @param {boolean} [vOptions.strict=false] Value representing if only <code>[object Objects]</code> are to be allowed.
* @param {boolean} [vOptions.allowFn=false] Value representing if functions are to be allowed.
* @param {boolean} [vOptions.allowJSON=false] Value representing if JSON-strings are to be allowed.
* @param {boolean} [vOptions.requiredKeys=undefined] Value listing the keys required to be present in the object.
* @param {boolean} [vOptions.interface=false] Value representing the required the keys and types (see: {@link: ish.type}).
* @returns {boolean} Value representing if the passed value represents an object.
*/ //#####
is: function isObj(x, vOptions) {
var fnTest, a_sInterfaceKeys, i, bReturnVal,
oSettings = (vOptions && vOptions === Object(vOptions) ? vOptions : {}),
a_sRequiredKeys = oSettings.requiredKeys,
oInterface = oSettings.interface,
bDisallowEmptyObject = !!(vOptions === true || oSettings.nonEmpty)
;
//# Call objBase to determine the validity of the passed o(bject), storing the results back in out o(bject) and bReturnVal
x = objBase(x, oSettings.allowFn, oSettings.allowJSON, oSettings.strict);
bReturnVal = x.b;
x = x.o;
//# If the passed o(bject) is valid
if (bReturnVal) {
//# Reset our bReturnVal based on bDisallowEmptyObject
bReturnVal = (!bDisallowEmptyObject || Object.keys(x).length !== 0);
//# If we still have a valid Object and we have a_sRequiredKeys, traverse them
if (bReturnVal && core.type.arr.is(a_sRequiredKeys, true)) {
for (i = 0; i < a_sRequiredKeys.length; i++) {
//# If the current a_sRequiredKeys is missing from our o(bject), flip our bReturnVal and fall from the loop
if (!x.hasOwnProperty(a_sRequiredKeys[0])) {
bReturnVal = false;
break;
}
}
}
//# If we still have a valid Object and we have an oInterface, collect it's a_sInterfaceKeys
//# NOTE: We use the lower-level call to Object.keys rather than core.type.arr.ownKeys as this is a lower-level ish function
if (bReturnVal && objBase(oInterface).b) {
a_sInterfaceKeys = Object.keys(oInterface);
//# Traverse the a_sInterfaceKeys, processing each to ensure they are present in the passed o(bject)
for (i = 0; i < a_sInterfaceKeys.length; i++) {
fnTest = oInterface[a_sInterfaceKeys[i]];
fnTest = (core.type.fn.is(fnTest) ? fnTest : core.resolve(core.type, [a_sInterfaceKeys[i], "is"]));
//# If the passed o(bject) doesn't have the current a_sInterfaceKeys or it's invalid per the current fnTest, reset our bReturnVal and fall from the loop
if (!x.hasOwnProperty(a_sInterfaceKeys[i]) || !core.type.fn.call(fnTest, null, x[a_sInterfaceKeys[i]])) {
bReturnVal = false;
break;
}
}
}
}
return bReturnVal;
}, //# obj.is
//#########
/** Casts the passed value into an object.
* @function ish.type.obj.mk
* @param {variant} x Value to interrogate.
* @param {variant} [vDefaultVal={}] Value representing the default return value if casting fails.
* @returns {object} Value representing the passed value as an object type.
*/ //#####
mk: function (x, vDefaultVal) {
//# If the passed o(bject) .is .str, try to .mkJSON
if (core.type.str.is(x, true)) {
x = mkJSON(x);
}
return (core.type.obj.is(x, { allowFn: true }) ?
x :
(arguments.length > 1 ? vDefaultVal : {})
);
}, //# obj.mk
};
}(); //# ish.type.obj
//#########
/** Symbol-based type functionality.
* @namespace ish.type.symbol
*/ //#####
//# NOTE: This base interface is more complicated than the others above due to the requirement of .exists and the use of .get and it's base function.
type.symbol = function () {
var fnReturnVal = function () {
return core.type.symbol.mk();
};
//#########
/** Safely returns a unique symbol, returning a unique object if <code>symbol</code> is not supported.
* @function ish.type.symbol.get
* @$aka ish.type.symbol
* @returns {symbol} Value representing a unique symbol or object.
*/ //#####
//# NOTE: fnReturnVal and .get have the same definition below but separate definitions to avoid ish.type.symbol.get having a recursive structure.
fnReturnVal.get = function () {
return core.type.symbol.mk();
};
//#########
/** Determines if the Symbol type is present in the current environment.
* @function ish.type.symbol.exists
* @returns {symbol} Value representing if the Symbol type is present in the current environment.
*/ //#####
fnReturnVal.exists = function () {
return (core.type.fn.is(_root.Symbol) && typeof _root.Symbol() === 'symbol');
}; //# symbol.exists
//#########
/** Determines if the passed value represents a symbol.
* @function ish.type.symbol.is
* @param {variant} x Value to interrogate.
* @returns {symbol} Value representing if the passed value represents a symbol.
*/ //#####
fnReturnVal.is = function isSymbol(x) {
//# NOTE: Since the typeof call is gated by .symbol.exists below, we need to selectively enable esnext for this function in JSHint below (besides, it's not a real error, just ES6 safety from JSHint)
/* jshint esnext: true */
return (core.type.symbol.exists() && typeof x === 'symbol');
}; //# symbol.is
//#########
/** Casts the passed value into a symbol.
* @function ish.type.symbol.mk
* @param {variant} x Value to interrogate.
* @param {variant} [vDefaultVal=Symbol()] Value representing the default return value if casting fails.
* @returns {symbol} Value representing the passed value as a symbol type.
*/ //#####
fnReturnVal.mk = function (x, vDefaultVal) {
return (core.type.symbol.is(x) ?
x :
(arguments.length <= 1 ?
//# If .symbol.exists, create a new Symbol(), optionally using the passed x if it .is .str, else use a new blank object if !.symbol.exists
(core.type.symbol.exists() ? _root.Symbol(core.type.str.is(x) ? x : _undefined) : {}) :
vDefaultVal
)
);
}; //# symbol.mk
return fnReturnVal;
}(); //# ish.type.symbol
return type;
}(); //# ish.type.*.is|mk
//################################################################################################
/** Provides access to (and optionally creates) an object structure's nested properties.
* @function ish.resolve
* @param {Symbol} [returnMetadata=!ish.resolve.returnMetadata] Value representing if metadata is to be returned; <code>{ value: {variant}, created: {boolean}, existed: {boolean} }</code>.
* @param {boolean} [bForceCreate=true] Value representing if the path is to be created if it doesn't already exist. <code>true</code> creates the path if it does not already exist.
* @param {object} oObject Value to interrogate.
* @param {string|string[]} vPath Value representing the path to the requested property as a period-delimited string (e.g. "parent.child.array.0.key") or an array of strings.
* @param {variant} [vValue] Value representing the value to set the referenced property to.
* @returns {variant} Value representing the variant at the referenced path.
* @example
* <caption>
* When forcing the creation of an object structure, data can be lost if an existing non-object property is used as a parent.
* <br/>This will overwrite the boolean property <code>nick</code> with an object reference containing the property <code>campbell</code>.
* </caption>
* var neek = { nick: true };
* var deepProp = ish.resolve(true, neek, "nick.campbell");
*/ //############################################################################################
core.resolve = function (/*[core.resolve.returnMetadata], [bForceCreate], oObject, vPath|a_sPath, [vValue]*/) {
var vReturnVal, vValue, vPath, oObject, a_sPath, i, bCurrentIsObj, bHaveValue, bForceCreate,
bPathExists = true,
oIsObjOptions = { allowFn: true },
a = Array.prototype.slice.call(arguments), //# NOTE: core.type.fn.convert(arguments) is not always available at this low-level :(
bReturnMetadata = (a[0] === core.resolve.returnMetadata),
bCreated = false,
isVal = function (v) {
return (v !== _null && v !== _undefined);
}
;
//# If a[0] is .returnMetadata, remove it from the a(rguments)
if (bReturnMetadata) {
a.shift();
}
//# Setup our local variables based on the passed a(rguments)
if (a[0] === true) {
bForceCreate = true;
oObject = a[1];
vPath = a[2];
//# If the caller passed in a vValue
if (a.length > 3) {
bHaveValue = true;
vValue = a[3];
}
} else {
bForceCreate = false;
oObject = a[0];
vPath = a[1];
//# If the caller passed in a vValue
if (a.length > 2) {
bHaveValue = true;
vValue = a[2];
}
}
//# Now that the passed oObject is known, set our vReturnVal accordingly
vReturnVal = (core.type.obj.is(oObject, oIsObjOptions) ? oObject : _undefined);
//# If the passed oObject .is .obj and vPath .is .str or .is .arr
if (isVal(oObject) && (core.type.str.is(vPath) || (core.type.arr.is(vPath, true) && core.type.str.is(vPath[0])))) {
//# Populate our a_sPath and reset our vReturnVal to the passed oObject (as it may be a native type with properties)
a_sPath = (core.type.arr.is(vPath) ? vPath : vPath.split("."));
vReturnVal = oObject;
//# Traverse the a_sPath
for (i = 0; i < a_sPath.length; i++) {
bCurrentIsObj = core.type.obj.is(vReturnVal, oIsObjOptions);
//# If the bCurrentIsObj
if (bCurrentIsObj) {
//# If the current vPath segment exists
if (a_sPath[i] in vReturnVal) {
//# Set oObject as the last object reference and vReturnVal as the current object reference
oObject = vReturnVal;
vReturnVal = oObject[a_sPath[i]];
}
//# Else if we are supposed to bForceCreate the current vPath segment
else if (bForceCreate) {
//# Set the oObject as the last object reference and create the new object at the current vPath segment while setting vReturnVal as the current object reference
oObject = vReturnVal;
vReturnVal = oObject[a_sPath[i]] = {};
bCreated = true;
}
//# Else the current vPath segment doesn't exist and we're not supposed to bForceCreate it, so reset our vReturnVal to undefined, flip bPathExists and fall from the loop
else {
vReturnVal = _undefined;
bPathExists = false;
break;
}
}
//# Else if we have an isVal in vReturnVal and the current a_sPath exists under it, set our vReturnVal to it
//# NOTE: We cannot use core.type.is.val below as this is a lower-level function
else if (isVal(vReturnVal) && vReturnVal[a_sPath[i]] !== _undefined) {
vReturnVal = vReturnVal[a_sPath[i]];
}
//# Else if we are bForce(ing)Create or we bHaveValue and this is the last index
else if (bForceCreate || (bHaveValue && i === a_sPath.length - 1)) {
//# Set a new object reference in vReturnVal then set it into oObject's last object reference
//# NOTE: We enter the outer loop knowing the initial vReturnVal bCurrentIsObj, so there is no need to worry about a [0 - 1] index below as we will never enter this if on the first loop
oObject[a_sPath[i]] = vReturnVal = {};
bCreated = true;
}
//# Else if we're not on the final vPath segment
else { //if (i < a_sPath.length - 1) {
//# The current vPath segment doesn't exist and we're not bForce(ing)Create, so reset our vReturnVal to undefined, flip bPathExists and fall from the loop
vReturnVal = _undefined;
bPathExists = false;
break;
}
}
//# If we bHaveValue and the bPathExists, set it now
if (bHaveValue && bPathExists) {
oObject[a_sPath[a_sPath.length - 1]] = vReturnVal = vValue;
}
}
return (
bReturnMetadata ? {
value: vReturnVal,
created: bCreated,
existed: (bPathExists && !bCreated)
} :
vReturnVal
);
}; //# ish.resolve
//#########
/** Unique value indicating if metadata is to be returned by <code>ish.resolve</code>.
* @property ish.resolve.returnMetadata
* @returns Value representing if metadata is to be returned by <code>ish.resolve</code>.
* @ignore
*/ //#####
core.resolve.returnMetadata = core.type.symbol();
//################################################################################################
/** Merges the content of the passed objects into the passed target, adding or overriding properties within the target.
* <span style="display: none;">Heavily refactored code from http://gomakethings.com/vanilla-javascript-version-of-jquery-extend/<span>
* @function ish.extend
* @param {boolean|integer} [vMaxDepth=true] Value representing if a deep copy is to occur. <code>false</code>/<code>1</code> performs a shallow copy, a positive integer indicates the max depth to perform a deep copy to, <code>true</code> and all other integer values perform a deep copy to an unlimited depth.
* @param {object|function} vTarget Value representing the target object to receive properties.
* @param {...object|...function} vSource Value(s) representing the source object(s) whose properties will be copied into the target.
* @returns {object|function} Value representing the passed target.
* @example
* <caption>
* Right-most source object wins:
* </caption>
* var oResult = ish.extend({}, { i: 1 }, { i: 2 }); // `oResult.i` will equal `2`.
*/ //############################################################################################
core.extend = function (/*[vMaxDepth], vTarget, vSource, vSource2...*/) {
var a_sKeys, oTarget, oSource, sKey, iExtendDepth, i, j, k, bOverMaxDepth,
a = arguments,
//fnIsDom = core.type.fn.mk(core.resolve(core, "type.dom.is")),
fnHasOwnProp = function (oPassedSource, sPassedKey) {
return Object.prototype.hasOwnProperty.call(oPassedSource, sPassedKey);
}
;
//# If the first argument .is .int or .bool, setup the local vars accordingly
if (core.type.int.is(a[0]) || core.type.bool.is(a[0])) {
iExtendDepth = (
a[0] === true ?
0 :
a[0] === false ?
1 :
core.type.int.mk(a[0])
);
oTarget = a[1];
i = 2;
}
//# Else the first argument is our oTarget, so setup the local vars accordingly
else {
iExtendDepth = 0;
oTarget = a[0];
i = 1;
}
//# Ensure our oTarget is an object
oTarget = (core.type.obj.is(oTarget, { allowFn: true }) ? oTarget : {}); //# Object(oTarget)
//# Traverse the passed oSource objects
for (/*i = i*/; i < a.length; i++) {
oSource = a[i];
a_sKeys = Object.keys(oSource || {});
//# If the oSource .is a .fn and the oTarget doesn't have that sKey yet, copy it in as-is (ignoring iExtendDepth as we can't copy functions)