-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathcompatibility.js
3273 lines (2914 loc) · 102 KB
/
compatibility.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
/**
* @name CeL function for compatibility
* @fileoverview 本檔案包含了 new ECMAScript standard 標準已規定,但先前版本未具備的內建物件功能;以及相容性 test
* 專用的 functions。<br />
* ES6 shim / polyfill<br />
* 部分標準功能已經包含於 ce.js。
*
* @see see Set, Map @ _structure/dependency_chain.js
*
* 注意: 本檔案可能會被省略執行,因此不應有標準之外的設定,應將之放置於 data.native。
*
* More examples: see /_test suite/test.js
*
* @since
* @see https://www.audero.it/blog/2016/12/05/monkey-patching-javascript/
* @see https://tc39.es/proposal-collection-methods/
* @see https://github.com/tc39/proposals
* @see https://github.com/Financial-Times/polyfill-library/tree/master/polyfills
* @see <a
* href="http://msdn.microsoft.com/en-us/library/s4esdbwz%28v=VS.85%29.aspx"
* accessdate="2010/4/16 20:4">Version Information (Windows Scripting -
* JScript)</a> http://espadrine.github.io/New-In-A-Spec/es2017/
*/
'use strict';
// 'use asm';
// --------------------------------------------------------------------------------------------
typeof CeL === 'function' && CeL.run({
// module name
name : 'data.code.compatibility',
// This module should NOT require other modules!
// nothing required.
// 本 module 為許多 module 所用,應盡可能勿 requiring 其他 module。
// require : '',
// 設定不匯出的子函式。
// no_extend : '*',
// 為了方便格式化程式碼,因此將 module 函式主體另外抽出。
code : module_code
});
function module_code(library_namespace) {
/**
* null module constructor
*
* @class 標準已規定,但先前版本未具備的功能;以及相容性 test 專用的 functions。
*/
var _// JSDT:_module_
= function() {
// null module constructor
};
/**
* for JSDT: 有 prototype 才會將之當作 Class
*/
_// JSDT:_module_
.prototype = {};
// cache
var Array_slice = Array.prototype.slice,
// cache
set_method = library_namespace.set_method,
/**
* The index return when not found.<br />
* 未發現之index。未找到時的 index。基本上與程式碼設計合一,僅表示名義,不可更改。(=== -1)
*
* @type {Number}
* @constant
*/
NOT_FOUND = ''.indexOf('_');
// ----------------------------------------------------------------------------------------------------------------------------------------------------------//
/**
* TODO:
*
* http://www.comsharp.com/GetKnowledge/zh-CN/It_News_K875.aspx<br />
* 8進制數字表示被禁止, 010 代表 10 而不是 8
*
* http://jquerymobile.com/gbs/
*/
var main_version = 0, full_version = '';
// for IE/NS only
if (typeof window !== 'undefined' && window.ScriptEngine) {
library_namespace.debug(library_namespace
.is_type(ScriptEngineMajorVersion), 2);
main_version = window.ScriptEngineMajorVersion() + '.'
+ window.ScriptEngineMinorVersion();
full_version = window.ScriptEngine() + ' ' + main_version + '.'
+ window.ScriptEngineBuildVersion();
main_version = Number(main_version);
} else if (false
// java test: 加了下面這段在 FF3 會召喚出 java! IE中沒有java object.
// old: object, new: function (?)
// && (typeof java == 'function' || typeof java == 'object') && java
) {
library_namespace.debug("Today is "
+ java.text.SimpleDateFormat("EEEE-MMMM-dd-yyyy").format(
new java.util.Date()));
if (main_version = java.lang.System.getProperty('os.name') + ' '
+ java.lang.System.getProperty('os.version') + ' '
+ java.lang.System.getProperty('os.arch'))
full_version = main_version;
else
main_version = 0;
}
if (full_version)
library_namespace.debug('Script engine: ' + full_version);
/**
* 版本檢查.
*
* @param {Number}version
* 最低 version
*/
function check_version(version) {
if (!library_namespace.is_digits(version) || version < 5)
version = 5;
if (typeof WScript !== 'undefined' && WScript.Version < version) {
// WScript.FullName, WScript.Path
var Locale = library_namespace.env.locale, promptTitle = Locale == 0x411 ? 'アップグレードしませんか?'
: '請升級', promptC = Locale == 0x411 ? "今使ってる "
+ WScript.Name
+ " のバージョンは古過ぎるから、\nMicrosoft Windows スクリプト テクノロジ Web サイトより\nバージョン "
+ WScript.Version + " から " + version + " 以上にアップグレードしましょう。"
: "正使用的 " + WScript.Name
+ " 版本過舊,\n請至 Microsoft Windows 網站將版本由 "
+ WScript.Version + " 升級到 " + version + " 以上。", url = /* Locale==0x411? */"http://www.microsoft.com/japan/developer/scripting/default.htm";
if (1 == WScript.Popup(promptC, 0, promptTitle, 1 + 48))
WshShell.Run(url);
WScript.Quit(1);
}
}
// ----------------------------------------------------------------------------------------------------------------------------------------------------------//
// global object
var globalThis = library_namespace.env.global;
if (false && (!globalThis.global || globalThis.global !== globalThis)) {
// Object.defineProperty() defined in base.js
Object.defineProperty(globalThis, 'global', {
configurable : true,
enumerable : false,
value : globalThis,
writable : false
});
}
if (!globalThis.globalThis || globalThis.globalThis !== globalThis) {
// e.g., node-v10.19.0
// Object.defineProperty() defined in base.js
Object.defineProperty(globalThis, 'globalThis', {
configurable : true,
enumerable : false,
value : globalThis,
writable : false
});
}
set_method(globalThis, {
encodeURI : escape,
decodeURI : unescape,
encodeURIComponent : encodeURI,
decodeURIComponent : decodeURI,
isNaN : function(value) {
// parseFloat(value)
// var a = typeof value == 'number' ? value : parseInt(value);
// alert(typeof a + ',' + a + ',' + (a === a));
/**
* 變數可以與其本身比較。如果比較結果不相等,則它會是 NaN。原因是 NaN 是唯一與其本身不相等的值。
*
* A reliable way for ECMAScript code to test if a value X is a NaN
* is an expression of the form X !== X. The result will be true if
* and only if X is a NaN.
*/
// return /* typeof value=='number'&& */a != a;
value = Number(value);
return value !== value;
},
// isFinite(null) === true
isFinite : function isFinite(value) {
// https://tc39.es/ecma262/#sec-isfinite-number
return Number.isFinite(Number(value));
}
}, null);
// ----------------------------------------------------------------------------------------------------------------------------------------------------------//
// Object.*
if (typeof Object.freeze === 'function')
try {
// https://github.com/es-shims/es5-shim/blob/master/es5-sham.js
Object.freeze(function() {
});
} catch (e) {
var Object_freeze = Object.freeze;
Object.freeze = function freeze_Object(object) {
return typeof object == 'function' ? Object_freeze(object)
: object;
};
}
if (!Object.setPrototypeOf) {
(function() {
var Object_getPrototypeOf, Object_setPrototypeOf;
// test prototype chain
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Inheritance_and_the_prototype_chain
if ({
__proto__ : []
} instanceof Array) {
// http://ejohn.org/blog/objectgetprototypeof/
// https://github.com/zloirock/core-js/blob/master/packages/core-js/internals/object-set-prototype-of.js
// https://github.com/wesleytodd/setprototypeof/blob/master/index.js
// https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/GetPrototypeOf
// http://perfectionkills.com/how-ecmascript-5-still-does-not-allow-to-subclass-an-array/
Object_getPrototypeOf = function get__proto__Of(object) {
return object.__proto__;
};
Object_setPrototypeOf = function set__proto__Of(object,
prototype) {
object.__proto__ = prototype;
return object;
};
} else if ({}.constructor && {}.constructor.prototype) {
Object_getPrototypeOf = function(object) {
return object.constructor.prototype;
};
Object_setPrototypeOf = function(object, prototype) {
object.constructor.prototype = prototype;
return object;
};
}
if (Object_getPrototypeOf) {
set_method(Object, {
getPrototypeOf : Object_getPrototypeOf,
setPrototypeOf : Object_setPrototypeOf
});
}
})();
}
// IE 8, JScript 5.8.23141 中,DOM 可能沒有 .hasOwnProperty()。
var hasOwnProperty = Object.prototype.hasOwnProperty
// Object.getOwnPropertyDescriptor(object, 'property')
|| function hasOwnProperty(key) {
try {
// Object.getPrototypeOf() 返回給定對象的原型。
var prototype = Object.getPrototypeOf(this);
return (key in this) && prototype
//
&& (!(key in prototype) || this[key] !== prototype[key]);
} catch (e) {
// TODO: handle exception
}
};
// Object.keys(): get Object keys, 列出對象中所有可以枚舉的屬性 (Enumerable Only)
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/keys
// 可用來防止 .prototype 帶來之 properties。e.g., @ IE
// cf. Object.getOwnPropertyNames() 會列出對象中所有可枚舉以及不可枚舉的屬性 (enumerable or
// non-enumerable)
function Object_keys(object) {
var keys = [];
try {
for ( var key in object) {
if (Object.hasOwn(object, key))
keys.push(key);
}
} catch (e) {
// TODO: handle exception
}
return keys;
}
/**
* @deprecatred
*/
function getPropertyNames() {
return Object.keys(this);
}
function getOwnPropertyDescriptor(object, property) {
if (Object.hasOwn(object, property)) {
return {
configurable : true,
enumerable : true,
value : object[property],
writable : true
};
}
}
function getOwnPropertyDescriptors(object) {
var descriptors = Object.create(null);
// for...in 循環也枚舉原型鏈中的屬性
for ( var property in object) {
var descriptor = Object.getOwnPropertyDescriptor(object, property);
if (descriptor)
descriptors[property] = descriptor;
}
return descriptors;
}
// https://tc39.github.io/ecma262/#sec-object.values
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/values
// http://www.2ality.com/2015/11/stage3-object-entries.html
// Object.values()
function Object_values(object) {
var values = [];
for (var keys = Object.keys(object), index = 0, length = keys.length; index < length; index++) {
values.push(object[keys[index]]);
}
return values;
return Object.keys(object).map(function(key) {
return object[key];
});
}
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries
// Object.entries()
function Object_entries(object) {
var entries = [];
for (var keys = Object.keys(object), index = 0, length = keys.length; index < length; index++) {
var key = keys[index];
entries.push([ key, object[key] ]);
}
return entries;
return Object.keys(object).map(function(key) {
// [ key, value ]
return [ key, object[key] ];
});
}
// Object.fromEntries()
function fromEntries(iterable) {
var object = Object.create(null);
iterable.forEach(function(pair) {
// pair = [ key, value ]
object[pair[0]] = pair[1];
});
return object;
}
set_method(Object, {
// 鎖定物件。
// Object.seal()
seal : function seal(object) {
// 無法以舊的語法實現。
return object;
},
// Object.isSealed()
isSealed : function isSealed(object) {
// 若欲更嚴謹些,可依照經驗法則,避開無法測試的 write-only 物件、或一改變就會產生後續影響的 object,
// 並對 object 作變更測試,確保 object 真的具有不可變更之性質。
return false;
},
// Object.preventExtensions()
preventExtensions : function preventExtensions(object) {
// 無法以舊的語法實現。
return object;
},
// Object.isExtensible()
isExtensible : function isExtensible(object) {
return true;
},
// Object.freeze()
freeze : function freeze(object) {
// 無法以舊的語法實現。
return object;
},
// Object.isFrozen()
isFrozen : function isFrozen(object) {
// 無法以舊的語法實現。
return false;
},
// Object.is(): Return SameValue(value_1, value_2).
// 以 SameValue Algorithm 判斷。
is : function is(value_1, value_2) {
return value_1 === value_2 ? value_1 !== 0
// check +0 and -0
|| 1 / value_1
// 為 JsDoc 換行。
=== 1 / value_2
// check NaN. May use Number.isNaN() as well.
: value_1 !== value_1 && value_2 !== value_2;
},
// Object.fromEntries()
fromEntries : fromEntries,
// Object.keys(): get Object keys, 列出對象中所有可以枚舉的屬性 (enumerable only)
keys : Object_keys,
values : Object_values,
entries : Object_entries,
// Object.hasOwn(object, property)
// https://github.com/tc39/proposal-accessible-object-hasownproperty
hasOwn : function hasOwn(object, property) {
return hasOwnProperty.call(object, property);
},
// Object.getOwnPropertyDescriptor()
getOwnPropertyDescriptor : getOwnPropertyDescriptor,
// Object.getOwnPropertyDescriptors()
getOwnPropertyDescriptors : getOwnPropertyDescriptors,
// Object.getOwnPropertyNames()
// 會列出對象中所有可枚舉以及不可枚舉的屬性 (enumerable or non-enumerable)
// 列出的比 Object.keys() 多
getOwnPropertyNames : Object_keys
});
// 會造成幾乎每個使用 for(.. in Object),而不是使用 Object.keys() 的,都出現問題。
if (false)
set_method(Object.prototype, {
// getPropertyNames : getPropertyNames,
hasOwnProperty : hasOwnProperty
});
// ----------------------------------------------------------------------------------------------------------------------------------------------------------//
// Array.*
// Array.prototype.at(), String.prototype.at(), typed_array.at()
// https://github.com/tc39/proposal-relative-indexing-method#polyfill
function get_item_at(index) {
index = ToInteger(index);
var length = this.length;
// Allow negative indexing from the end
if (index < 0)
index += length;
// incase (a=[])[-3]=3;a.at(-3);
if (0 <= index && index < length) {
// typeof this === 'object' @ HTA (HTML Application) @ Windows 10
// return this instanceof String ? this.charAt(index) : this[index];
return this.charAt ? this.charAt(index) : this[index];
}
}
// 稀疏矩陣 (sparse matrix) 用的 Array.prototype.some()
// 要到 index > 1e7 比較感覺得出來。
// e.g.,
// a=[];a[1e7]=2;alert(a.some(function(v){return v===2}));
// a=[];a[1e7]=2;alert(a.sparse_some(function(v){return v===2}));
function sparse_some(callback, thisArg) {
for ( var index in this)
if (!isNaN(index))
if (thisArg ? callback.call(thisArg, this[index], index, this)
// 不採用 .call() 以加速執行。
: callback(this[index], index, this))
return true;
return false;
}
// 稀疏矩陣 (sparse matrix) 用的 Array.prototype.every()
// 要到 index > 1e7 比較感覺得出來。
function sparse_every(callback, thisArg) {
for ( var index in this)
if (!isNaN(index))
if (!(thisArg ? callback
.call(thisArg, this[index], index, this)
// 不採用 .call() 以加速執行。
: callback(this[index], index, this)))
return false;
return true;
}
// 測試 for ( ... in array ) 時,會依順序提供 index。
if (typeof Array.prototype.some !== 'function')
(function() {
var array = [], result = [];
array[4] = 4;
array[2] = 2;
array[0] = 0;
for ( var index in array)
if (!isNaN(index))
result.push(index);
// CeL.log(result.join());
if (library_namespace.env.sequenced_Array = result.join() === '0,2,4')
set_method(Array.prototype, {
sparse_some : sparse_some,
sparse_every : sparse_every
});
})();
set_method(Array, {
// Array.of()
of : function of() {
return Array_slice.call(arguments);
}
});
function normalize_position(position, length) {
return position < 0 && (position += length) < 0 ? 0
//
: (position |= 0) > length ? length : position;
}
// Array.prototype.copyWithin(target, start[, end = this.length])
function copyWithin(target, start, end) {
var length = this.length;
start = normalize_position(start, length);
end = normalize_position(end || length, length);
target = normalize_position(target, length);
if (target < start || end <= target)
while (start < end)
this[target++] = this[start++];
else if (target !== start) {
if (length < target + start) {
end -= target - start;
target = length;
} else
target += start;
// 反向(後→前) copy,確保 copy from 不曾被本操作汙染過。
while (start < end)
this[--target] = this[--end];
}
return this;
}
// https://github.com/tc39/proposal-flatMap
function flat(depth) {
if (depth === undefined)
depth = 1;
else
depth |= 0;
var array = [];
function push_item(_this, _depth) {
_depth--;
_this.forEach(function(item) {
if (_depth >= 0 && Array.isArray(item))
push_item(item, _depth);
else
array.push(item);
});
}
push_item(this, depth);
return array;
}
function flatMap(mapperFunction, thisArg) {
if (false) {
return this.map(
thisArg ? mapperFunction.bind(thisArg) : mapperFunction)
.flat();
}
var array = [];
this.forEach(function(item) {
item = thisArg ? mapperFunction.call(thisArg, item)
: mapperFunction(item);
if (Array.isArray(item))
item.forEach(function(_item) {
array.push(_item);
});
else
array.push(item);
});
return array;
}
set_method(Array.prototype, {
/** <code>Array.prototype.copyWithin(target, start [ , end ])</code> */
copyWithin : copyWithin,
// https://github.com/tc39/proposal-relative-indexing-method#polyfill
at : get_item_at,
// Array.prototype.includes()
// part of the Harmony (ECMAScript 7) proposal.
// http://www.2ality.com/2016/01/ecmascript-2016.html
includes : function Array_includes(search_target, position) {
if (search_target === search_target)
return this.indexOf(search_target, position) !== NOT_FOUND;
// assert: search_target is NaN
var length = this.length;
// position = normalize_position(position, length);
if (position < 0 && (position += length) < 0)
position = 0;
else if ((position |= 0) > length)
position = length;
for (; position < length; position++)
if (this[position] !== this[position])
return true;
return false;
},
// Array.prototype.reduce()
reduce : function reduce(callbackfn/* , initialValue */) {
var index = 0, length = this.length, value;
if (arguments.length > 1)
value = arguments[1];
else
// initialValue
for (; index < length; index++)
if (index in this) {
value = this[index++];
break;
}
for (; index < length; index++)
if (index in this)
value = callbackfn(value, this[index], index, this);
return value;
},
// Array.prototype.reduceRight()
reduceRight : function reduceRight(callbackfn
// , initialValue
) {
var index = this.length, value;
if (arguments.length > 1)
value = arguments[1];
else
// initialValue
while (index-- > 0)
if (index in this) {
value = this[index];
break;
}
while (index-- > 0)
if (index in this)
value = callbackfn(value, this[index], index, this);
return value;
},
// Array.prototype.entries()
entries : function entries() {
// new Array_Iterator(array, use value)
return new library_namespace.Array_Iterator(this);
},
// Array.prototype.values()
values : function values() {
// new Array_Iterator(array, use value)
return new library_namespace.Array_Iterator(this, true);
},
// Array.prototype.keys()
keys : function Array_keys() {
var keys = [];
for ( var key in this)
if (/^\d+$/.test(key))
keys.push(key | 0);
library_namespace.debug('keys: ' + keys, 5,
//
'Array.prototype.keys');
return new library_namespace.Array_Iterator(keys, true);
},
// Array.prototype.findIndex()
findIndex : function findIndex(predicate, thisArg) {
for (var index = 0, length = this.length; index < length; index++)
if (index in this)
if (thisArg ? predicate.call(thisArg, this[index], index,
this)
// 不採用 .call() 以加速執行。
: predicate(this[index], index, this))
return index;
return NOT_FOUND;
},
// Array.prototype.find()
find : function find(predicate, thisArg) {
var index = this.findIndex(predicate, thisArg);
if (index !== NOT_FOUND)
return this[index];
// return undefined;
},
// https://github.com/tc39/proposal-array-find-from-last
// Array.prototype.findLastIndex()
findLastIndex : function findLastIndex(predicate, thisArg) {
for (var index = this.length; index > 0;)
if (--index in this)
if (thisArg ? predicate.call(thisArg, this[index], index,
this)
// 不採用 .call() 以加速執行。
: predicate(this[index], index, this))
return index;
return NOT_FOUND;
},
// Array.prototype.findLast()
findLast : function findLast(predicate, thisArg) {
var index = this.findLastIndex(predicate, thisArg);
if (index !== NOT_FOUND)
return this[index];
// return undefined;
},
// Array.prototype.some()
some : function some(callback, thisArg) {
for (var index = 0, length = this.length; index < length; index++)
if (index in this)
if (thisArg ? callback.call(thisArg, this[index], index,
this)
// 不採用 .call() 以加速執行。
: callback(this[index], index, this))
return true;
return false;
},
// Array.prototype.every()
every : function every(callback, thisArg) {
for (var index = 0, length = this.length; index < length; index++)
if (index in this)
if (!(thisArg ? callback.call(thisArg, this[index], index,
this)
// 不採用 .call() 以加速執行。
: callback(this[index], index, this)))
return false;
return true;
},
// Array.prototype.map()
map : function map(callback, thisArg) {
var result = [];
this.forEach(function() {
result.push(callback.apply(this, arguments));
}, thisArg);
return result;
},
// Array.prototype.filter()
filter : function map(callback, thisArg) {
var result = [];
this.forEach(function(value) {
if (callback.apply(this, arguments))
result.push(value);
}, thisArg);
return result;
},
// Array.prototype.flat
flat : flat,
// Array.prototype.flatMap
flatMap : flatMap,
// Array.prototype.indexOf ( searchElement [ , fromIndex ] )
indexOf : function indexOf(searchElement, fromIndex) {
fromIndex |= 0;
var length = this.length;
if (fromIndex < 0 && (fromIndex += length) < 0)
fromIndex = 0;
for (; fromIndex < length; fromIndex++)
if (searchElement === this[fromIndex])
return fromIndex;
return NOT_FOUND;
},
// Array.prototype.lastIndexOf ( searchElement [ , fromIndex ] )
lastIndexOf : function lastIndexOf(searchElement, fromIndex) {
var length = this.length;
if (isNaN(fromIndex))
fromIndex = length - 1;
else if ((fromIndex |= 0) < 0)
fromIndex += length;
else
fromIndex = Math.min(fromIndex, length - 1);
for (; 0 <= fromIndex; fromIndex--)
if (searchElement === this[fromIndex])
return fromIndex;
return NOT_FOUND;
},
// Array.prototype.fill()
fill : function fill(value, start, end) {
// Array.prototype.fill() 只會作用於 0~原先的 length 範圍內!
if (isNaN(end) || this.length < (end |= 0))
end = this.length;
else if (end < 0)
end += this.length;
for (var index = start || 0; index < end;)
this[index++] = value;
return this;
},
/**
* 對於舊版沒有 Array.push() 等函數時之判別及處置。<br />
* 不能用t=this.valueOf(); ... this.push(t);
*/
// Array.prototype.push()
push : function push() {
var i = 0, l = arguments.length, w = this.length;
// 在 FF3 僅用 this[this.length]=o; 效率略好於 Array.push(),
// 但 Chrome 6 相反。
for (; i < l; i++)
this[w++] = arguments[i];
return w;
},
// Array.prototype.pop()
pop : function pop() {
// 不能用 return this[--this.length];
var l = this.length, v;
if (l) {
v = this[l];
this.length--;
}
return v;
},
// Array.prototype.shift()
shift : function shift() {
var v = this[0];
// ECMAScript 不允許設定 this=
this.value = this.slice(1);
return v;
},
// Array.prototype.unshift()
unshift : function unshift() {
// ECMAScript 不允許設定 this =
this.value = Array_slice.call(arguments).concat(this);
return this.length;
}
}, null);
// ----------------------------------------------------------------------------------------------------------------------------------------------------------//
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays
// It's hard to fully simulate typed arrays.
// 只能把原先即存在的功能加強到可用。
var typed_arrays = [];
if (typeof Uint32Array === 'function')
(function() {
var Array_prototype = Array.prototype,
// TODO: .slice() and others
typed_array_methods = 'copyWithin,entries,every,fill,filter,find,findIndex,forEach,includes,indexOf,join,keys,lastIndexOf,map,reduce,reduceRight,reverse,set,slice,some,subarray,values,at'
.split(',');
'Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array'
//
.split(',').forEach(function(typed_array) {
try {
typed_array = eval(typed_array);
} catch (e) {
library_namespace.warn('Not exist: ' + typed_array);
return;
}
var prototype = typed_array.prototype;
typed_array_methods.forEach(function(method) {
if (!(method in typed_array.prototype))
Object.defineProperty(prototype, method, {
value : Array_prototype[method]
});
});
typed_arrays.push(typed_array);
});
})();
if (typed_arrays.length === 0)
typed_arrays = null;
_.typed_arrays = typed_arrays;
// ----------------------------------------------------------------------------------------------------------------------------------------------------------//
// Number.*
// 1. === 1.0
function ToNumber(value) {
// Number(value)
return +value;
}
// cf. value | 0
/** <code>((Number.MAX_SAFE_INTEGER / 4) | 0) < 0, 0 < ((Number.MAX_SAFE_INTEGER / 5) | 0)</code> */
function ToInteger(value) {
return Math.trunc(value) || 0;
// return value >> 0;
// https://tc39.es/ecma262/#sec-tointeger
value = Number(value);
return value > 0 ? Math.floor(value) : value < 0 ? -Math.floor(value)
: 0;
}
// Number.isNaN()
// http://wiki.ecmascript.org/doku.php?id=harmony:number.isnan
function is_NaN(value) {
return typeof value === 'number' &&
// isNaN(value)
value !== value;
}
// calculatable
/**
* 取得最小最低可做除法計算數值。回傳值為邊界,已不可再做操作。但可做乘法操作。
*
* @param [base_integral]
* @returns {Number}
*/
function dividable_minimum(base_integral, return_last) {
if (!base_integral || isNaN(base_integral))
base_integral = 1;
var last = 1, min;
// 預防 min 變成0,因此設置前一步 last。
while (base_integral !== base_integral + (min = last / 2))
last = min;
return !return_last && min || last;
}
// calculatable
/**
* 取得最大可做加法計算數值。回傳值為邊界,已不可再做加法操作。但可做減法操作。
*
* @param [base_integral]
* @returns {Integer}
*/
function addable_maximum(base_integral) {
if (!base_integral || isNaN(base_integral))
base_integral = 1;
var max = 1, test;
while ((max *= 2) < (test = max + base_integral)
&& max === test - base_integral)
;
return max;
}
var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || addable_maximum() - 1;
// Number.isSafeInteger()
function isSafeInteger(number) {
return typeof number === 'number'
// && number <= MAX_SAFE_INTEGER && -MAX_SAFE_INTEGER <= number
&& Math.abs(number) <= MAX_SAFE_INTEGER
// 在範圍外的,常常 % 1 亦為 0。
&& 0 === number % 1
// && Math.floor(number) === number
;
}
set_method(Number, {
/**
* The value of Number.MAX_SAFE_INTEGER is the largest integer value
* that can be represented as a Number value without losing precision,
* which is 9007199254740991 (2^53-1).
*/
MAX_SAFE_INTEGER : MAX_SAFE_INTEGER,
/**
* The value of Number.MIN_SAFE_INTEGER is -9007199254740991
* (-(2^53-1)).
*/
MIN_SAFE_INTEGER : -MAX_SAFE_INTEGER,
/**
* The value of Number.EPSILON is the difference between 1 and the
* smallest value greater than 1 that is representable as a Number
* value, which is approximately 2.2204460492503130808472633361816 x
* 10-16.
*/
EPSILON : dividable_minimum(0, 1)
}, 'number');
set_method(Number, {
isSafeInteger : isSafeInteger,
/**
* Number.toInteger() is obsolete.
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toInteger
* Number.toInteger was part of the draft ECMAScript 6 specification,
* but has been removed on August 23, 2013 in Draft Rev 17.
*/
// toInteger: ToInteger,
/**
* Number.isInteger()<br />
* cf. .is_digits()
*/
isInteger : function isInteger(number) {
// https://tc39.es/ecma262/#sec-number.isinteger
return Number.isFinite(number)
// Math.floor(Infinity) === Infinity
&& ToInteger(number) === number;
},
parseFloat : parseFloat,
parseInt : parseInt,
/**
* Number.isNaN()
*/
isNaN : is_NaN,
isFinite : function isFinite(value) {
return typeof value === 'number' && !isNaN(value)
&& value !== Infinity && value !== -Infinity;
}
});
// ----------------------------------------------------------------------------------------------------------------------------------------------------------//
// Math.*
// https://rwaldron.github.io/proposal-math-extensions/