forked from microsoft/devicescript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbasic.ts
More file actions
1253 lines (1108 loc) · 26.8 KB
/
basic.ts
File metadata and controls
1253 lines (1108 loc) · 26.8 KB
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
import * as ds from "@devicescript/core"
import { assert, _panic } from "@devicescript/core"
function isClose(x: number, y: number): void {
if (isNaN(x) && isNaN(y)) return
const d = Math.abs(x - y)
if (d < 0.00000001 || d / Math.abs(x + y) < 0.00001) return
console.log(x, " !== ", y, "!")
_panic(108)
}
function isEq(x: any, y: any): void {
// console.log(x, " === ", y, "?")
if (x !== y) {
console.log(ds.format("fail: {0} !== {1}", x, y))
_panic(109)
}
}
function strEq(a: string, b: string) {
if (a !== b) {
console.log(`fail: '${a}' !== '${b}'`)
_panic(110)
}
}
let x = 0
let glb1 = 0
function testFlow() {
x = 1
if (x !== 1) _panic(1)
if (x !== 1) _panic(1)
if (x === 1) {
x = 2
if (x !== 2) _panic(3)
} else {
_panic(2)
}
x = 1
if (x < 1) _panic(1)
if (x > 1) _panic(1)
if (x >= 1) {
} else _panic(1)
if (x <= 1) {
} else _panic(1)
if (x < 0.5) _panic(1)
if (x > 1.5) _panic(1)
if (0 <= x && x <= 2) {
} else _panic(1)
if (0 <= x || x < 1) {
} else _panic(1)
if (x < 0 || x > 10) _panic(1)
x = -1
if (Math.abs(x) !== 1) _panic(4)
x = Math.random()
if (x < 0 || x > 1 || isNaN(x)) _panic(5)
x = 42
console.log("rand=", Math.random())
isEq(ds.SystemStatusCodes.CalibrationNeeded, 100)
}
function testMath() {
// these are here to avoid constant folding
let v0 = 0
let v1 = 1
let v2 = 2
let v3 = 3
let v7 = 7
let v10 = 10
let v100 = 100
let vffff = 0xffff
// TODO use let ... to avoid constant folding
isEq(v2 + 2, 4)
isEq(v2 - 1, 1)
isClose(v3 * 4 + 3, 15.00001)
isEq(Math.abs(v10), 10)
isEq(Math.abs(-v10), 10)
isEq(Math.abs(v0), 0)
isClose(Math.log(Math.E), 1)
isClose(Math.log(1.23456), 0.21071463)
isClose(Math.log(-v1), NaN)
isClose(v0 / 0, NaN)
isClose(Math.log2(Math.PI), 1.651496129)
isClose(Math.log10(Math.PI), 0.49714987269)
isClose(Math.pow(v2, 0.5), Math.SQRT2)
isClose(v2 ** 0.5, Math.SQRT2)
isClose(Math.sqrt(v1 / 2), Math.SQRT1_2)
isClose(Math.cbrt(27), 3)
isClose(Math.exp(v1), Math.E)
isClose(Math.exp(v10), 22026.4657948)
isEq(Math.ceil(0.1), 1)
isEq(Math.ceil(0.9), 1)
isEq(Math.floor(1.1), 1)
isEq(Math.floor(1.9), 1)
isEq(Math.round(1.9), 2)
isEq(Math.round(1.3), 1)
isEq(Math.min(1, 7.1), 1)
isEq(Math.min(1.2, 1.2), 1.2)
isEq(Math.min(-1, -7), -7)
isEq(Math.max(1, 7), 7)
isEq(Math.max(1, 1), 1)
isEq(Math.max(-1, -7), -1)
isEq(fib(8), 21)
isEq(fibx(8), 21)
isEq(v1 & 3, 1)
isEq(v1 & 0, 0)
isEq(v1 & 2, 0)
isEq(v1 | 3, 3)
isEq(v1 | 0, 1)
isEq(v1 | 2, 3)
isEq(v1 ^ 3, 2)
isEq(v1 ^ 0, 1)
isEq(v1 ^ 2, 3)
isEq(~-v3, 2)
isEq(~v100, -101)
isEq(v1 << 2, 4)
isEq(16 >> v3, 2)
isEq(16 >>> v3, 2)
isEq(-16 >> v3, -2)
isEq(-16 >>> v3, 536870910)
isEq(v10 << -1, 0)
isEq(v10 << 0, 10)
isEq(v10 << 0.5, 10)
isEq(v10 << 1.7, 20)
isEq(v10 << 2.1, 40)
isEq(v10 << 100, 160)
isEq(v10 << 20, 10485760)
isEq(v10 << 30, -2147483648)
isEq(v10 << 31, 0)
isEq(v10 << 32, 10)
isEq(v10 << 33, 20)
isEq(v10 << 34, 40)
isEq(v1 << -1, -2147483648)
let v102 = 102
let v7ffff = 0x7ffff
isEq(Math.imul(v10, 30), 300)
isEq(Math.imul(vffff, 0xffff), -131071)
isEq(Math.imul(vffff, 0xffff1), -2031601)
isEq(Math.imul(vffff, 0xffff11), -32440081)
isEq(Math.imul(vffff, 0xffff111), -518975761)
isEq(Math.imul(vffff, 0x7fff1111), -1861095697)
isEq(Math.imul(v7ffff, 0x7fff1111), 143191791)
isEq(Math.idiv(100, v10), 10)
isEq(Math.idiv(102, v10), 10)
isEq(Math.idiv(-102, v10), -10)
isEq(Math.idiv(v102, 7), 14)
isEq(Math.idiv(-v102, 7), -14)
}
function lazyX(v: number) {
x = x + 1 + v
return v
}
function checkX(v: number) {
if (x !== v) {
console.log(ds.format("{0} !== {1} !!", x, v))
_panic(11)
}
x = 0
}
function testLazy() {
x = 0
if (lazyX(0) || lazyX(1)) {
checkX(3)
} else {
_panic(10)
}
if (lazyX(0) && lazyX(1)) {
_panic(10)
} else {
checkX(1)
}
if (lazyX(NaN) && lazyX(1)) {
_panic(101)
} else {
if (!isNaN(x)) _panic(12)
}
}
function fib(k: number): number {
if (k < 2) return k
const r = fib(k - 1) + fib(k - 2)
return r
}
function fibx(k: number): number {
if (k < 2) return k
return fibx(k - 1) + fibx(k - 2)
}
function testBuffer() {
const buf = Buffer.alloc(20)
buf.setAt(2, "u32", 0xf00d)
isEq(buf.getAt(2, "u32"), 0xf00d)
isEq(buf.getAt(2, "u16"), 0xf00d)
isEq(buf.getAt(2, "u8"), 0x0d)
isEq(buf.getAt(3, "u8"), 0xf0)
isEq(buf[3], 0xf0)
buf.setAt(8, "u22.10", 123.8274)
isClose(buf.getAt(8, "u22.10"), 123.8274)
isEq(buf.getAt(8, "u32"), 126799)
buf[2] = 7
isEq(buf[2], 7)
buf[4] = 0x13
const b2 = hex`72 33 23 12`
buf.blitAt(0, b2, 0, 10)
isEq(buf[0], 0x72)
isEq(buf[3], 0x12)
isEq(buf[4], 0x13)
buf.blitAt(2, b2, 1, 1)
isEq(buf[0], 0x72)
isEq(buf[1], 0x33)
isEq(buf[2], 0x33)
isEq(buf[3], 0x12)
isEq(buf[4], 0x13)
const b3 = hex`
72 // comment
33 23 // something
12`
isEq(b2.toString("hex"), b3.toString("hex"))
const buf2 = hex`01 02 03 04`.slice()
buf2.rotate(1)
isEq(buf2.toString("hex"), "02030401")
buf2.rotate(-1)
isEq(buf2.toString("hex"), "01020304")
buf2.rotate(1, 0, 2)
isEq(buf2.toString("hex"), "02010304")
buf2.rotate(-1, 0, 2)
isEq(buf2.toString("hex"), "01020304")
buf2.rotate(-10, 1, 3)
isEq(buf2.toString("hex"), "01020304")
buf2.rotate(-1, 1, 4)
isEq(buf2.toString("hex"), "01040203")
buf2.rotate(1, 1, 4)
buf2.rotate(-4, 1, 4)
isEq(buf2.toString("hex"), "01040203")
}
function three(a: number, b: number, c: number) {
return a / b + c
}
function testArray() {
let arr = []
isEq(arr.length, 0)
arr = [1, 2, 3]
isEq(arr.length, 3)
isEq(arr[0], 1)
isEq(arr[1], 2)
isEq(arr[2], 3)
isEq(arr[3], undefined)
isEq(arr[-1], undefined)
arr[4] = 12
isEq(arr.length, 5)
isEq(arr[3], undefined)
isEq(arr[4], 12)
arr = []
arr.push(10)
isEq(arr.length, 1)
isEq(arr[0], 10)
isEq(arr[1], undefined)
isEq(arr.push(20), 2)
isEq(arr[1], 20)
const [a, b, c, ...rest] = arr
isEq(a, 10)
isEq(b, 20)
isEq(c, undefined)
isEq(rest.length, 0)
const [aa, ...bb] = arr
isEq(aa, 10)
isEq(bb.length, 1)
isEq(bb[0], 20)
}
function testObjInner(x: any) {
const { foo: fo, bar } = x
isEq(fo, 7)
isEq(bar, 13)
}
function testObj() {
const obj: any = {
bar: 13,
}
obj.foo = 5
isEq(obj.foo, 5)
isEq(obj.bar, 13)
obj.foo = 7
isEq(obj.foo, 7)
isEq(obj.bar, 13)
testObjInner(obj)
return obj
}
function objEq(a: any, b: any) {
if (a === b) return
const ka = Object.keys(a)
const kb = Object.keys(b)
isEq(ka.length, kb.length)
let i = 0
while (i < ka.length) {
const k = ka[i]
isEq(a[k], b[k])
i = i + 1
}
}
function testSpread() {
const obj: any = {
bar: 13,
}
Object.assign(obj, { foo: 5 })
isEq(obj.foo, 5)
isEq(obj.bar, 13)
const qq = { foo: 1, ...obj, bar: 3 }
isEq(qq.foo, 5)
isEq(qq.bar, 3)
isEq(delete qq.bar2, false)
isEq(delete qq.bar, true)
isEq(delete qq.bar, false)
isEq(Object.keys(qq).length, 1)
isEq(qq.foo, 5)
isEq(qq.bar, undefined)
const o2 = { a: 1, b: 2, c: 3 }
{
const { a, ...r0 } = o2
isEq(a, 1)
objEq(r0, { b: 2, c: 3 })
}
{
const { a, b, ...r0 } = o2
isEq(a, 1)
isEq(b, 2)
objEq(r0, { c: 3 })
}
isEq(three(10, 2, 7), 12)
const arr: [number, number, number] = [10, 2, 7]
isEq(three(...arr), 12)
const arr2: [number, number] = [2, 7]
isEq(three(10, ...arr2), 12)
const tmp1 = [1, 2]
tmp1.pushRange(tmp1)
isEq(tmp1.length, 4)
}
function testConsole() {
// note that we don't really test the output ...
let n = 8
let q = 12
console.log("text" + n)
console.log("text" + n + q)
console.log("text" + n + "blah" + q)
console.log("text" + (n + q))
console.log(`text ${n + q}`)
console.log(`text ${n} x ${q}`)
console.log(`text ${n} + ${q} is`, n + q)
}
function testString() {
let a = "a"
let colon = ":"
strEq(a + "b", "ab")
strEq(a + 1, "a1")
strEq(1 + a, "1a")
strEq(colon + true, ":true")
strEq(colon + false, ":false")
strEq(colon + null, ":null")
strEq(colon + 1.4, ":1.4")
strEq(colon + NaN, ":NaN")
const b = Buffer.alloc(3)
b[0] = 0x42
b[1] = 0x6c
strEq(":" + b, ":[Buffer[3] 426c00]")
strEq(`x${1}`, "x1")
strEq(`x${true}x`, "xtruex")
strEq(`x ${null} x`, "x null x")
}
let gl = 0
function testClo(b: (one?: number) => () => void) {
gl = 0
isEq(gl, 0)
const q = b(1)
isEq(gl, 4)
q()
isEq(gl, 5)
q()
isEq(gl, 6)
}
function testClosures1() {
const foo = function foo() {
let q = 1
const bar = () => {
gl = q
q = q + 1
}
isEq(gl, 0)
bar()
isEq(gl, 1)
q = q + q
bar()
isEq(gl, 4)
return bar
}
testClo(foo)
}
function testClosures2() {
const foo = function foo() {
let q = 1
const qux = () => {
const bar = () => {
gl = q
q = q + 1
}
return bar
}
const bar = qux()
isEq(gl, 0)
bar()
isEq(gl, 1)
q = q + q
bar()
isEq(gl, 4)
return bar
}
testClo(foo)
}
function testClosures3() {
const foo = function foo(q: number) {
const bar = () => {
gl = q
q = q + 1
}
isEq(gl, 0)
bar()
isEq(gl, 1)
q = q + q
bar()
isEq(gl, 4)
return bar
}
testClo(foo)
}
function testForOf() {
let coll2 = [1, 2]
if (coll2) {
} else _panic(111)
let tmp = coll2
let sum = 0
for (const e of coll2) {
if (coll2 !== null) coll2.push(17)
coll2 = null
sum += e
}
isEq(sum, 20)
isEq(tmp.length, 3)
}
function testInstanceOf() {
const err = new Error()
const tperr = new TypeError()
isEq(err instanceof Error, true)
isEq(err instanceof TypeError, false)
isEq(tperr instanceof TypeError, true)
isEq(tperr instanceof Error, true)
isEq(tperr instanceof RangeError, false)
isEq(err instanceof RangeError, false)
isEq(err instanceof Object, true)
isEq(tperr instanceof Object, true)
const obj = {}
isEq(obj instanceof Object, true)
isEq(obj instanceof Error, false)
const json = JSON.parse("{}")
isEq(json instanceof Object, true)
isEq(json instanceof Error, false)
const foo = new Foo(12)
isEq(foo instanceof Object, true)
isEq(foo instanceof Foo, true)
}
class Foo {
str: string
constructor(public num: number) {
this.str = "blah"
}
stringify() {
return `${this.num}/${this.str}`
}
unused() {}
}
class Bar extends Foo {
override stringify(): string {
return `hello ${this.num} ${this.str}`
}
}
class Baz extends Foo {
constructor() {
super(77)
}
}
function callStr(q: Foo) {
return q.stringify()
}
function testClass() {
const f = new Foo(12)
isEq(callStr(f), "12/blah")
f.str = "bb"
isEq(callStr(f), "12/bb")
isEq(callStr(new Bar(13)), "hello 13 blah")
isEq(callStr(new Baz()), "77/blah")
}
function testFunName() {
const b = new Bar(12)
isEq(ds.reboot.name, "reboot")
isEq(b.constructor.name, "Bar")
isEq(b.stringify.name, "stringify")
isEq(qq.name, "qq")
isEq(testFunName.name, "testFunName")
let e = new TypeError("blah")
// isEq(e.constructor, TypeError) TODO
isEq(e.constructor.name, "TypeError")
isEq(e.name, "TypeError")
e = new Error("blah")
// isEq(e.constructor, Error) TODO
isEq(e.constructor.name, "Error")
isEq(e.name, "Error")
function qq() {}
}
function expectErr(js: string) {
try {
JSON.parse(js)
} catch {
return
}
throw new Error(`expecting error on: ${js}`)
}
function jsonTest(js: string, indent?: number) {
const o = JSON.parse(js)
const str = JSON.stringify(o, null, indent)
if (js !== str) {
console.log(`orig:${js}`)
console.log(`stri:${str}`)
console.log(`stri2:${JSON.stringify(str)}`)
throw new Error("failed JSON")
}
const o2 = JSON.parse(" " + js + " ")
ds.assert(JSON.stringify(o2) === JSON.stringify(o))
expectErr(js + "x")
expectErr(js + "t")
if (typeof o !== "number") {
expectErr(js.slice(0, -1))
expectErr(js.slice(0, -2))
expectErr(js.slice(1))
}
}
function testDeflUndefinedForNumber(f: number, g?: number) {
isEq(f, 3)
ds.assert(g == null, "n3")
ds.assert(g === undefined, "n3")
}
function testJSON() {
console.log("testJSON")
jsonTest("null")
jsonTest("true")
jsonTest("false")
jsonTest("12")
jsonTest("-12")
jsonTest("-12.5")
jsonTest("{}")
jsonTest("[]")
jsonTest("[1]")
jsonTest('{"x":1}')
jsonTest('{"x":1,"y":[1,2,3]}')
jsonTest('{"x":1,"y":[]}')
jsonTest("[{}]")
jsonTest("[{},{}]")
jsonTest("[null,{}]")
jsonTest('[{"foo":1,"a":[]}]')
jsonTest("[]", 2)
jsonTest("[\n 1\n]", 2)
jsonTest("[\n 1,\n 3\n]", 2)
jsonTest("{}", 2)
jsonTest('{\n "x": 1\n}', 2)
jsonTest('{\n "x": 1,\n "y": [\n 1,\n 2,\n 3\n ]\n}', 2)
isEq(JSON.stringify({ x: 1, y: undefined }), '{"x":1}')
isEq(JSON.stringify({ x: 1, y: () => {} }), '{"x":1}')
testDeflUndefinedForNumber(3)
let strings = ["foo", "foo\n", '"', "\b\t\r\n", ""]
for (let s of strings) {
ds.assert(JSON.parse(JSON.stringify(s)) === s, s)
}
ds.assert(JSON.parse('"\\u000A\\u0058\\u004C\\u004d"') === "\nXLM", "uni")
let ss = ds._id("12") + "34"
ds.assert(ss.slice(1) === "234", "sl0")
ds.assert(ss.slice(1, 2) === "2", "sl1")
ds.assert(ss.slice(-2) === "34", "sl2")
ds.assert(ss.slice(1, 0) === "", "sl3")
ds.assert(ss.slice(1, -1) === "23", "sl4")
}
function testAnySwitch() {
function bar(x: number) {
glb1 += x
return x
}
function testIt(v: number) {
glb1 = 0
switch (v) {
case bar(0):
return 1
default:
return 7
case bar(1):
return 2
case bar(2):
return 3
}
}
function ss() {
return ds._id("f7") + "4n"
}
function testStr(s: string) {
switch (s) {
case "foo":
return 0
case ss():
return 2
case "bar":
return 1
default:
return 7
}
}
function testQuick(v: number) {
switch (v) {
default:
return 7
case 0:
return 1
case 1:
return 2
case bar(2):
return 3
case 3:
return 4
case 4:
return 5
case 5:
return 6
}
}
function testFallThrough(x: number) {
let r = ""
switch (x) {
// @ts-ignore
default:
r += "q"
// fallthrough
case 6:
// @ts-ignore
case 7:
r += "x"
// fallthrough
case 8:
r += "y"
break
case 10:
r += "z"
break
}
return r
}
function switchLoop() {
let r = ""
for (let i = 0; i < 5; ++i) {
switch (i) {
case 0:
case 1:
r += "x"
break
case 2:
continue
}
r += i
}
isEq(r, "x0x134")
}
let v = testIt(2)
isEq(v, 3)
isEq(glb1, 3)
v = testIt(0)
isEq(v, 1)
isEq(glb1, 0)
isEq(testStr("foo"), 0)
isEq(testStr("bar"), 1)
isEq(testStr(ss()), 2)
for (let i = 0; i <= 6; ++i) isEq(testQuick(i), i + 1)
isEq(testFallThrough(100), "qxy")
isEq(testFallThrough(6), "xy")
isEq(testFallThrough(7), "xy")
isEq(testFallThrough(8), "y")
isEq(testFallThrough(10), "z")
switchLoop()
}
class AssertionError extends RangeError {
constructor(matcher: string, message: string) {
super()
this.name = "AssertionError"
this.message = `${matcher}: ${message}`
}
}
function testBuiltinExtends() {
const a = new AssertionError("a", "b")
ds.assert(a instanceof Error)
ds.assert(a instanceof RangeError)
ds.assert(a instanceof AssertionError)
ds.assert(a.name === "AssertionError")
}
function testUndef() {
ds.assert(console.log("foo") === undefined)
}
interface XYZ {
x: number
y: string
z?: number
}
function testDestructArg() {
function foo({ x, y, z }: XYZ) {
ds.assert(x === 1)
ds.assert(y === "foo")
ds.assert(z === undefined)
}
function apply<T>(v: T, f: (v: T) => void) {
f(v)
}
apply({ x: 1, y: 2 }, ({ x, y }) => {
ds.assert(x === 1)
ds.assert(y === 2)
})
foo({ x: 1, y: "foo" })
}
function testClosurePP() {
let idx = 1
function foo() {
idx++
}
foo()
foo()
ds.assert(idx === 3)
}
async function testSetTimeout() {
let q = 1
let id = 0
await ds.delay(1)
setTimeout(() => {
ds.assert(q === 1)
console.log(`clear ${id}`)
clearTimeout(id)
q = 2
}, 10)
setTimeout(() => {
ds.assert(q === 2)
q = 3
}, 31)
id = setTimeout(() => {
q = 17
}, 64)
await ds.delay(100)
ds.assert(q === 3, `expected 3, got ${q}`)
id = setInterval(() => {
q = q + 1
if (q === 5) clearInterval(id)
}, 5)
await ds.sleep(60)
ds.assert(q === 5)
}
function testShift() {
const arr = ["baz", ds._id("foo") + "bar"]
ds.assert(arr.shift() === "baz")
ds.assert(arr.shift() === "foobar")
ds.assert(arr.shift() === undefined)
}
let numRestArgs = 0
function s0(...args: number[]) {
isEq(args.length, numRestArgs)
for (let i = 0; i < args.length; ++i) isEq(args[i], i + 1)
}
function s1(a0: number, ...args: number[]) {
args.unshift(a0)
isEq(args.length, numRestArgs)
for (let i = 0; i < args.length; ++i) isEq(args[i], i + 1)
}
function testRest() {
numRestArgs = 0
s0()
s0(...[])
numRestArgs = 1
s0(1)
s0(...[1])
s1(1)
;(s1 as any)(...[1])
numRestArgs = 2
s0(1, 2)
s0(...[1, 2])
s1(1, 2)
s1(1, ...[2])
}
class Node {
constructor() {}
}
class SuiteNode extends Node {
children: string[] = []
constructor() {
super()
}
}
async function testFibers() {
let i = 0
async function logloop() {
while (true) {
i++
await ds.sleep(9)
}
}
async function resumeMe(f: ds.Fiber) {
await ds.sleep(10)
f.resume(20)
}
await ds.sleep(10)
const f0 = ds.Fiber.self()
const f1 = logloop.start()
ds.assert(f0 !== f1)
await ds.sleep(50)
f1.terminate()
console.log(i)
ds.assert(4 <= i && i <= 6)
const i0 = i
await ds.sleep(50)
ds.assert(i === i0)
resumeMe.start(f0)
const r = await ds.suspend<number>(30)
ds.assert(r === 20)
console.log("fibers OK!")
}
class FooError extends Error {}
function testCtorError() {
try {
throw new FooError("blah")
} catch (e: any) {
ds.assert(e.message === "blah")
}
}
function testIgnoredAnd() {
let q = 0
function foo() {
q++
}
foo && foo()
ds.assert(q === 1)
}
function expectTypeError(f: () => void) {
let ok = false
try {
f()
} catch (e) {
ds.assert(e instanceof TypeError)
ok = true
}
ds.assert(ok)
}
function testQDot() {
let q: any = null
let i = 0
ds.assert(q?.foo === undefined)
ds.assert(q?.foo[i++] === undefined)
ds.assert(i === 0)
ds.assert(q?.foo.bar === undefined)
expectTypeError(() => {
const tmp = (q?.foo).bar
})
q = {}
ds.assert(q?.foo?.bar === undefined)
expectTypeError(() => {
const tmp = q?.foo.bar
})
q = () => {
i = 7
}
q?.()
ds.assert(i === 7)
q = undefined
i = 3
q?.()[i++]
ds.assert(i === 3)
}
function testHex() {
ds.assert(Buffer.from("żółw").toString("hex") === "c5bcc3b3c58277")
ds.assert(Buffer.from([1, 2]).toString("hex") === "0102")
ds.assert(Buffer.from("aa").toString("hex") === "6161")
expectTypeError(() => {
console.log(Buffer.from("aa").toString("foobar" as any))
})
}