-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjswrap_array.c
924 lines (845 loc) · 27.5 KB
/
jswrap_array.c
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
/*
* This file is part of Espruino, a JavaScript interpreter for Microcontrollers
*
* Copyright (C) 2013 Gordon Williams <[email protected]>
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* ----------------------------------------------------------------------------
* This file is designed to be parsed during the build process
*
* JavaScript methods for Arrays
* ----------------------------------------------------------------------------
*/
#include "jswrap_array.h"
#include "jsparse.h"
#define min(a,b) (((a)<(b))?(a):(b))
#define max(a,b) (((a)>(b))?(a):(b))
/*JSON{
"type" : "class",
"class" : "Array",
"check" : "jsvIsArray(var)"
}
This is the built-in JavaScript class for arrays.
Arrays can be defined with ```[]```, ```new Array()```, or ```new Array(length)```
*/
/*JSON{
"type" : "constructor",
"class" : "Array",
"name" : "Array",
"generate" : "jswrap_array_constructor",
"params" : [
["args","JsVarArray","The length of the array OR any number of items to add to the array"]
],
"return" : ["JsVar","An Array"]
}
Create an Array. Either give it one integer argument (>=0) which is the length of the array, or any number of arguments
*/
JsVar *jswrap_array_constructor(JsVar *args) {
assert(args);
if (jsvGetArrayLength(args)==1) {
JsVar *firstArg = jsvSkipNameAndUnLock(jsvGetArrayItem(args,0));
if (jsvIsInt(firstArg) && jsvGetInteger(firstArg)>=0) {
JsVarInt count = jsvGetInteger(firstArg);
if (count>0) {
JsVar *arr = jsvNewWithFlags(JSV_ARRAY);
if (!arr) return 0; // out of memory
jsvSetArrayLength(arr, count, false);
jsvUnLock(firstArg);
return arr;
}
}
jsvUnLock(firstArg);
}
// Otherwise, we just return the array!
return jsvLockAgain(args);
}
/*JSON{
"type" : "method",
"class" : "Array",
"name" : "toString",
"generate" : "jswrap_object_toString",
"params" : [
["radix","JsVar","unused"]
],
"return" : ["JsVar","A String representing the array"]
}
Convert the Array to a string
*/
/*JSON{
"type" : "property",
"class" : "Array",
"name" : "length",
"generate" : "jswrap_object_length",
"return" : ["JsVar","The value of the array"]
}
Find the length of the array
*/
/*JSON{
"type" : "method",
"class" : "Array",
"name" : "indexOf",
"generate" : "jswrap_array_indexOf",
"params" : [
["value","JsVar","The value to check for"]
],
"return" : ["JsVar","the index of the value in the array, or -1"]
}
Return the index of the value in the array, or -1
*/
JsVar *jswrap_array_indexOf(JsVar *parent, JsVar *value) {
JsVar *idxName = jsvGetArrayIndexOf(parent, value, false/*not exact*/);
// but this is the name - we must turn it into a var
if (idxName == 0) return jsvNewFromInteger(-1); // not found!
JsVar *idx = jsvCopyNameOnly(idxName, false/* no children */, false/* Make sure this is not a name*/);
jsvUnLock(idxName);
return idx;
}
/*JSON{
"type" : "method",
"class" : "Array",
"name" : "join",
"generate" : "jswrap_array_join",
"params" : [
["separator","JsVar","The separator"]
],
"return" : ["JsVar","A String representing the Joined array"]
}
Join all elements of this array together into one string, using 'separator' between them. eg. ```[1,2,3].join(' ')=='1 2 3'```
*/
JsVar *jswrap_array_join(JsVar *parent, JsVar *filler) {
if (!jsvIsIterable(parent)) return 0;
if (jsvIsUndefined(filler))
filler = jsvNewFromString(","); // the default it seems
else
filler = jsvAsString(filler, false);
if (!filler) return 0; // out of memory
JsVar *str = jsvArrayJoin(parent, filler);
jsvUnLock(filler);
return str;
}
/*JSON{
"type" : "method",
"class" : "Array",
"name" : "push",
"generate" : "jswrap_array_push",
"params" : [
["arguments","JsVarArray","One or more arguments to add"]
],
"return" : ["int","The new size of the array"]
}
Push a new value onto the end of this array'
*/
JsVarInt jswrap_array_push(JsVar *parent, JsVar *args) {
if (!jsvIsArray(parent)) return -1;
JsVarInt len = -1;
JsvObjectIterator it;
jsvObjectIteratorNew(&it, args);
while (jsvObjectIteratorHasValue(&it)) {
JsVar *el = jsvObjectIteratorGetValue(&it);
len = jsvArrayPush(parent, el);
jsvUnLock(el);
jsvObjectIteratorNext(&it);
}
jsvObjectIteratorFree(&it);
if (len<0)
len = jsvGetArrayLength(parent);
return len;
}
/*JSON{
"type" : "method",
"class" : "Array",
"name" : "pop",
"generate_full" : "jsvArrayPop(parent)",
"return" : ["JsVar","The value that is popped off"]
}
Pop a new value off of the end of this array
*/
JsVar *_jswrap_array_iterate_with_callback(const char *name, JsVar *parent, JsVar *funcVar, JsVar *thisVar, bool wantArray, bool isBoolCallback, bool expectedValue) {
if (!jsvIsIterable(parent)) {
jsExceptionHere(JSET_ERROR, "Array.%s can only be called on something iterable", name);
return 0;
}
if (!jsvIsFunction(funcVar)) {
jsExceptionHere(JSET_ERROR, "Array.%s's first argument should be a function", name);
return 0;
}
if (!jsvIsUndefined(thisVar) && !jsvIsObject(thisVar)) {
jsExceptionHere(JSET_ERROR, "Array.%s's second argument should be undefined, or an object", name);
return 0;
}
JsVar *result = 0;
if (wantArray)
result = jsvNewWithFlags(JSV_ARRAY);
bool isDone = false;
if (result || !wantArray) {
JsvIterator it;
jsvIteratorNew(&it, parent);
while (jsvIteratorHasElement(&it) && !isDone) {
JsVar *index = jsvIteratorGetKey(&it);
if (jsvIsInt(index)) {
JsVarInt idxValue = jsvGetInteger(index);
JsVar *args[3], *cb_result;
args[0] = jsvIteratorGetValue(&it);
args[1] = jsvNewFromInteger(idxValue); // child is a variable name, create a new variable for the index
args[2] = parent;
cb_result = jspeFunctionCall(funcVar, 0, thisVar, false, 3, args);
jsvUnLock(args[0]);
jsvUnLock(args[1]);
if (cb_result) {
bool matched;
if (isBoolCallback)
matched = (jsvGetBool(cb_result) == expectedValue);
if (wantArray) {
if (isBoolCallback) { // filter
if (matched) {
jsvArrayPushAndUnLock(result, jsvIteratorGetValue(&it));
}
} else { // map
JsVar *name = jsvNewFromInteger(idxValue);
if (name) { // out of memory?
jsvMakeIntoVariableName(name, cb_result);
jsvAddName(result, name);
jsvUnLock(name);
}
}
} else {
// break the loop early if expecting a particular value and didn't get it
if (isBoolCallback && !matched)
isDone = true;
}
jsvUnLock(cb_result);
}
}
jsvUnLock(index);
jsvIteratorNext(&it);
}
jsvIteratorFree(&it);
}
/* boolean result depends on whether the loop terminated
early for 'some' or completed for 'every' */
if (!wantArray && isBoolCallback) {
result = jsvNewFromBool(isDone != expectedValue);
}
return result;
}
/*JSON{
"type" : "method",
"class" : "Array",
"name" : "map",
"generate" : "jswrap_array_map",
"params" : [
["function","JsVar","Function used to map one item to another"],
["thisArg","JsVar","if specified, the function is called with 'this' set to thisArg (optional)"]
],
"return" : ["JsVar","An array containing the results"]
}
Return an array which is made from the following: ```A.map(function) = [function(A[0]), function(A[1]), ...]```
*/
JsVar *jswrap_array_map(JsVar *parent, JsVar *funcVar, JsVar *thisVar) {
return _jswrap_array_iterate_with_callback("map", parent, funcVar, thisVar, true, false, false);
}
/*JSON{
"type" : "method",
"class" : "Array",
"name" : "forEach",
"generate" : "jswrap_array_forEach",
"params" : [
["function","JsVar","Function to be executed"],
["thisArg","JsVar","if specified, the function is called with 'this' set to thisArg (optional)"]
]
}
Executes a provided function once per array element.
*/
void jswrap_array_forEach(JsVar *parent, JsVar *funcVar, JsVar *thisVar) {
_jswrap_array_iterate_with_callback("forEach", parent, funcVar, thisVar, false, false, false);
}
/*JSON{
"type" : "method",
"class" : "Array",
"name" : "filter",
"generate" : "jswrap_array_filter",
"params" : [
["function","JsVar","Function to be executed"],
["thisArg","JsVar","if specified, the function is called with 'this' set to thisArg (optional)"]
],
"return" : ["JsVar","An array containing the results"]
}
Return an array which contains only those elements for which the callback function returns 'true'
*/
JsVar *jswrap_array_filter(JsVar *parent, JsVar *funcVar, JsVar *thisVar) {
return _jswrap_array_iterate_with_callback("filter", parent, funcVar, thisVar, true, true, true);
}
/*JSON{
"type" : "method",
"class" : "Array",
"name" : "some",
"generate" : "jswrap_array_some",
"params" : [
["function","JsVar","Function to be executed"],
["thisArg","JsVar","if specified, the function is called with 'this' set to thisArg (optional)"]
],
"return" : ["JsVar","A boolean containing the result"]
}
Return 'true' if the callback returns 'true' for any of the elements in the array
*/
JsVar *jswrap_array_some(JsVar *parent, JsVar *funcVar, JsVar *thisVar) {
return _jswrap_array_iterate_with_callback("some", parent, funcVar, thisVar, false, true, false);
}
/*JSON{
"type" : "method",
"class" : "Array",
"name" : "every",
"generate" : "jswrap_array_every",
"params" : [
["function","JsVar","Function to be executed"],
["thisArg","JsVar","if specified, the function is called with 'this' set to thisArg (optional)"]
],
"return" : ["JsVar","A boolean containing the result"]
}
Return 'true' if the callback returns 'true' for every element in the array
*/
JsVar *jswrap_array_every(JsVar *parent, JsVar *funcVar, JsVar *thisVar) {
return _jswrap_array_iterate_with_callback("every", parent, funcVar, thisVar, false, true, true);
}
/*JSON{
"type" : "method",
"class" : "Array",
"name" : "reduce",
"ifndef" : "SAVE_ON_FLASH",
"generate" : "jswrap_array_reduce",
"params" : [
["callback","JsVar","Function used to reduce the array"],
["initialValue","JsVar","if specified, the initial value to pass to the function"]
],
"return" : ["JsVar","The value returned by the last function called"]
}
Execute `previousValue=initialValue` and then `previousValue = callback(previousValue, currentValue, index, array)` for each element in the array, and finally return previousValue.
*/
JsVar *jswrap_array_reduce(JsVar *parent, JsVar *funcVar, JsVar *initialValue) {
const char *name = "reduce";
if (!jsvIsIterable(parent)) {
jsExceptionHere(JSET_ERROR, "Array.%s can only be called on something iterable", name);
return 0;
}
if (!jsvIsFunction(funcVar)) {
jsExceptionHere(JSET_ERROR, "Array.%s's first argument should be a function", name);
return 0;
}
JsVar *previousValue = jsvLockAgainSafe(initialValue);
JsvIterator it;
jsvIteratorNew(&it, parent);
if (!previousValue) {
bool isDone = false;
while (!isDone && jsvIteratorHasElement(&it)) {
JsVar *index = jsvIteratorGetKey(&it);
if (jsvIsInt(index)) {
previousValue = jsvIteratorGetValue(&it);
isDone = true;
}
jsvUnLock(index);
jsvIteratorNext(&it);
}
if (!previousValue) {
jsExceptionHere(JSET_ERROR, "Array.%s without initial value required non-empty array", name);
}
}
while (jsvIteratorHasElement(&it)) {
JsVar *index = jsvIteratorGetKey(&it);
if (jsvIsInt(index)) {
JsVarInt idxValue = jsvGetInteger(index);
JsVar *args[4];
args[0] = previousValue;
args[1] = jsvIteratorGetValue(&it);
args[2] = jsvNewFromInteger(idxValue); // child is a variable name, create a new variable for the index
args[3] = parent;
previousValue = jspeFunctionCall(funcVar, 0, 0, false, 4, args);
jsvUnLock(args[0]);
jsvUnLock(args[1]);
jsvUnLock(args[2]);
}
jsvUnLock(index);
jsvIteratorNext(&it);
}
jsvIteratorFree(&it);
return previousValue;
}
/*JSON{
"type" : "method",
"class" : "Array",
"name" : "splice",
"generate" : "jswrap_array_splice",
"params" : [
["index","int","Index at which to start changing the array. If negative, will begin that many elements from the end"],
["howMany","JsVar","An integer indicating the number of old array elements to remove. If howMany is 0, no elements are removed."],
["elements","JsVarArray","One or more items to add to the array"]
],
"return" : ["JsVar","An array containing the removed elements. If only one element is removed, an array of one element is returned."]
}
Both remove and add items to an array
*/
JsVar *jswrap_array_splice(JsVar *parent, JsVarInt index, JsVar *howManyVar, JsVar *elements) {
if (!jsvIsArray(parent)) return 0;
JsVarInt len = jsvGetArrayLength(parent);
if (index<0) index+=len;
if (index<0) index=0;
if (index>len) index=len;
JsVarInt howMany = len; // how many to delete!
if (jsvIsInt(howManyVar)) howMany = jsvGetInteger(howManyVar);
if (howMany > len-index) howMany = len-index;
JsVarInt newItems = jsvGetArrayLength(elements);
JsVarInt shift = newItems-howMany;
bool needToAdd = false;
JsVar *result = jsvNewWithFlags(JSV_ARRAY);
JsvObjectIterator it;
jsvObjectIteratorNew(&it, parent);
while (jsvObjectIteratorHasValue(&it) && !needToAdd) {
bool goToNext = true;
JsVar *idxVar = jsvObjectIteratorGetKey(&it);
if (idxVar && jsvIsInt(idxVar)) {
JsVarInt idx = jsvGetInteger(idxVar);
if (idx<index) {
// do nothing...
} else if (idx<index+howMany) { // must delete
if (result) { // append to result array
JsVar *el = jsvObjectIteratorGetValue(&it);
jsvArrayPushAndUnLock(result, el);
}
// delete
goToNext = false;
JsVar *toRemove = jsvObjectIteratorGetKey(&it);
jsvObjectIteratorNext(&it);
jsvRemoveChild(parent, toRemove);
jsvUnLock(toRemove);
} else { // we're greater than the amount we need to remove now
needToAdd = true;
goToNext = false;
}
}
jsvUnLock(idxVar);
if (goToNext) jsvObjectIteratorNext(&it);
}
// now we add everything
JsVar *beforeIndex = jsvObjectIteratorGetKey(&it);
JsvObjectIterator itElement;
jsvObjectIteratorNew(&itElement, elements);
while (jsvObjectIteratorHasValue(&itElement)) {
JsVar *element = jsvObjectIteratorGetValue(&itElement);
jsvArrayInsertBefore(parent, beforeIndex, element);
jsvUnLock(element);
jsvObjectIteratorNext(&itElement);
}
jsvObjectIteratorFree(&itElement);
jsvUnLock(beforeIndex);
// And finally renumber
while (jsvObjectIteratorHasValue(&it)) {
JsVar *idxVar = jsvObjectIteratorGetKey(&it);
if (idxVar && jsvIsInt(idxVar)) {
jsvSetInteger(idxVar, jsvGetInteger(idxVar)+shift);
}
jsvUnLock(idxVar);
jsvObjectIteratorNext(&it);
}
// free
jsvObjectIteratorFree(&it);
// and reset array size
jsvSetArrayLength(parent, len + shift, false);
return result;
}
/*JSON{
"type" : "method",
"class" : "Array",
"name" : "shift",
"ifndef" : "SAVE_ON_FLASH",
"generate" : "jswrap_array_shift",
"params" : [
],
"return" : ["JsVar","The element that was removed"]
}
Remove the first element of the array, and return it
*/
JsVar *jswrap_array_shift(JsVar *parent) {
// just use splice, as this does all the hard work for us
JsVar *nRemove = jsvNewFromInteger(1);
JsVar *elements = jsvNewWithFlags(JSV_ARRAY);
JsVar *arr = jswrap_array_splice(parent, 0, nRemove, elements);
jsvUnLock(elements);
jsvUnLock(nRemove);
// unpack element from the array
JsVar *el = 0;
if (jsvIsArray(arr))
el = jsvArrayPop(arr);
jsvUnLock(arr);
return el;
}
/*JSON{
"type" : "method",
"class" : "Array",
"name" : "unshift",
"ifndef" : "SAVE_ON_FLASH",
"generate" : "jswrap_array_unshift",
"params" : [
["elements","JsVarArray","One or more items to add to the beginning of the array"]
],
"return" : ["int","The new array length"]
}
Remove the first element of the array, and return it
*/
JsVarInt jswrap_array_unshift(JsVar *parent, JsVar *elements) {
// just use splice, as this does all the hard work for us
JsVar *nRemove = jsvNewFromInteger(0);
jsvUnLock(jswrap_array_splice(parent, 0, nRemove, elements));
jsvUnLock(nRemove);
// return new length
return jsvGetLength(parent);
}
/*JSON{
"type" : "method",
"class" : "Array",
"name" : "slice",
"generate" : "jswrap_array_slice",
"params" : [
["start","int","Start index"],
["end","JsVar","End index (optional)"]
],
"return" : ["JsVar","A new array"]
}
Return a copy of a portion of the calling array
*/
JsVar *jswrap_array_slice(JsVar *parent, JsVarInt start, JsVar *endVar) {
JsVarInt len = jsvGetLength(parent);
JsVarInt end = len;
if (!jsvIsUndefined(endVar))
end = jsvGetInteger(endVar);
JsVarInt k = 0;
JsVarInt final = len;
JsVar *array = jsvNewWithFlags(JSV_ARRAY);
if (!array) return 0;
if (start<0) k = max((len + start), 0);
else k = min(start, len);
if (end<0) final = max((len + end), 0);
else final = min(end, len);
bool isDone = false;
JsvIterator it;
jsvIteratorNew(&it, parent);
while (jsvIteratorHasElement(&it) && !isDone) {
JsVarInt idx = jsvGetIntegerAndUnLock(jsvIteratorGetKey(&it));
if (idx < k) {
jsvIteratorNext(&it);
} else {
if (k < final) {
jsvArrayPushAndUnLock(array, jsvIteratorGetValue(&it));
jsvIteratorNext(&it);
k++;
} else {
isDone = true;
}
}
}
jsvIteratorFree(&it);
return array;
}
/*JSON{
"type" : "staticmethod",
"class" : "Array",
"name" : "isArray",
"generate_full" : "jsvIsArray(var)",
"params" : [
["var","JsVar","The variable to be tested"]
],
"return" : ["bool","True if var is an array, false if not."]
}
Returns true if the provided object is an array
*/
NO_INLINE static bool _jswrap_array_sort_leq(JsVar *a, JsVar *b, JsVar *compareFn) {
if (compareFn) {
JsVar *args[2] = {a,b};
JsVarInt r = jsvGetIntegerAndUnLock(jspeFunctionCall(compareFn, 0, 0, false, 2, args));
return r<0;
} else {
JsVar *sa = jsvAsString(a, false);
JsVar *sb = jsvAsString(b, false);
bool r = jsvCompareString(sa,sb, 0, 0, false) < 0;
jsvUnLock(sa);
jsvUnLock(sb);
return r;
}
}
NO_INLINE static void _jswrap_array_sort(JsvIterator *head, int n, JsVar *compareFn) {
if (n < 2) return; // sort done!
JsvIterator pivot = jsvIteratorClone(head);
JsVar *pivotValue = jsvIteratorGetValue(&pivot);
/* We're just going to use the first entry (head) as the pivot...
* We'll move along with our iterator 'it', and if it < pivot then we'll
* swap the values over (hence moving pivot forwards) */
int nlo = 0, nhigh = 0;
JsvIterator it = jsvIteratorClone(head); //
jsvIteratorNext(&it);
/* Partition and count sizes. */
while (--n && !jspIsInterrupted()) {
JsVar *itValue = jsvIteratorGetValue(&it);
if (_jswrap_array_sort_leq(itValue, pivotValue, compareFn)) {
nlo++;
/* 'it' <= 'pivot', so we need to move it behind.
In this diagram, P=pivot, L=it
l l l l l P h h h h h L
| \ /
\ \_____/_
_\______/ \
/ | |
| | |
l l l l l L P h h h h h
It makes perfect sense now...
*/
// first, get the old pivot value and overwrite it with the iterator value
jsvIteratorSetValue(&pivot, itValue); // no unlock needed
// now move pivot forwards, and set 'it' to the value the new pivot has
jsvIteratorNext(&pivot);
jsvUnLock(jsvIteratorSetValue(&it, jsvIteratorGetValue(&pivot)));
// finally set the pivot iterator to the pivot's value again
jsvIteratorSetValue(&pivot, pivotValue); // no unlock needed
} else {
nhigh++;
// Great, 'it' > 'pivot' so it's in the right place
}
jsvUnLock(itValue);
jsvIteratorNext(&it);
}
jsvIteratorFree(&it);
jsvUnLock(pivotValue);
if (jspIsInterrupted()) return;
// now recurse
_jswrap_array_sort(head, nlo, compareFn);
jsvIteratorNext(&pivot);
_jswrap_array_sort(&pivot, nhigh, compareFn);
jsvIteratorFree(&pivot);
}
/*JSON{
"type" : "method",
"class" : "Array",
"name" : "sort",
"ifndef" : "SAVE_ON_FLASH",
"generate" : "jswrap_array_sort",
"params" : [
["var","JsVar","A function to use to compare array elements (or undefined)"]
],
"return" : ["JsVar","This array object"]
}
Do an in-place quicksort of the array
*/
JsVar *jswrap_array_sort (JsVar *array, JsVar *compareFn) {
if (!jsvIsUndefined(compareFn) && !jsvIsFunction(compareFn)) {
jsExceptionHere(JSET_ERROR, "Expecting compare function, got %t", compareFn);
return 0;
}
JsvIterator it;
/* Arrays can be sparse and the iterators don't handle this
(we're not going to mess with indices) so we have to count
up the number of elements manually.
FIXME: sort is broken for sparse arrays anyway (it basically
ignores all the 'undefined' entries). I wonder whether just
compacting the array down to start from 0 before we start would
fix this?
*/
int n=0;
if (jsvIsArray(array) || jsvIsObject(array)) {
jsvIteratorNew(&it, array);
while (jsvIteratorHasElement(&it)) {
n++;
jsvIteratorNext(&it);
}
jsvIteratorFree(&it);
} else {
n = (int)jsvGetLength(array);
}
jsvIteratorNew(&it, array);
_jswrap_array_sort(&it, n, compareFn);
jsvIteratorFree(&it);
return jsvLockAgain(array);
}
/*JSON{
"type" : "method",
"class" : "Array",
"name" : "concat",
"ifndef" : "SAVE_ON_FLASH",
"generate" : "jswrap_array_concat",
"params" : [
["args","JsVarArray","Any items to add to the array"]
],
"return" : ["JsVar","An Array"]
}
Create a new array, containing the elements from this one and any arguments, if any argument is an array then those elements will be added.
*/
JsVar *jswrap_array_concat(JsVar *parent, JsVar *args) {
JsVar *result = jsvNewWithFlags(JSV_ARRAY);
JsvObjectIterator argsIt;
jsvObjectIteratorNew(&argsIt, args);
// Append parent's elements first (parent is always an array)
JsVar *source = jsvLockAgain(parent);
do {
if (jsvIsArray(source)) {
JsvObjectIterator it;
jsvObjectIteratorNew(&it, source);
while (jsvObjectIteratorHasValue(&it)) {
jsvArrayPushAndUnLock(result, jsvObjectIteratorGetValue(&it));
jsvObjectIteratorNext(&it);
}
jsvObjectIteratorFree(&it);
} else
jsvArrayPush(result, source);
// Next, append arguments
jsvUnLock(source);
source = jsvObjectIteratorHasValue(&argsIt) ? jsvObjectIteratorGetValue(&argsIt) : 0;
jsvObjectIteratorNext(&argsIt);
} while (source);
jsvObjectIteratorFree(&argsIt);
return result;
}
/*JSON{
"type" : "method",
"class" : "Array",
"name" : "fill",
"ifndef" : "SAVE_ON_FLASH",
"generate" : "jswrap_array_fill",
"params" : [
["value","JsVar","The value to fill the array with"],
["start","int","Optional. The index to start from (or 0). If start is negative, it is treated as length+start where length is the length of the array"],
["end","JsVar","Optional. The index to end at (or the array length). If end is negative, it is treated as length+end."]
],
"return" : ["JsVar","This array"]
}
Fill this array with the given value, for every index `>= start` and `< end`
*/
JsVar *jswrap_array_fill(JsVar *parent, JsVar *value, JsVarInt start, JsVar *endVar) {
if (!jsvIsIterable(parent)) return 0;
JsVarInt length = jsvGetLength(parent);
if (start < 0) start = start + length;
if (start < 0) return 0;
JsVarInt end = jsvIsNumeric(endVar) ? jsvGetInteger(endVar) : length;
if (end < 0) end = end + length;
if (end < 0) return 0;
JsvIterator it;
jsvIteratorNew(&it, parent);
JsVarInt last = start;
while (jsvIteratorHasElement(&it) && !jspIsInterrupted()) {
JsVarInt idx = jsvGetIntegerAndUnLock(jsvIteratorGetKey(&it));
// as it could be a sparse array, we may have missed items out...
while (last<idx && !jspIsInterrupted()) {
if (last>=start && last<end) {
JsVar *namedChild = jsvMakeIntoVariableName(jsvNewFromInteger(last), value);
if (namedChild) {
jsvAddName(parent, namedChild);
jsvUnLock(namedChild);
}
}
last++;
}
if (idx>=start && idx<end) {
jsvIteratorSetValue(&it, value);
}
last = idx+1;
jsvIteratorNext(&it);
}
jsvIteratorFree(&it);
while (last<end && !jspIsInterrupted()) {
if (last>=start) {
JsVar *namedChild = jsvMakeIntoVariableName(jsvNewFromInteger(last), value);
if (namedChild) {
jsvAddName(parent, namedChild);
jsvUnLock(namedChild);
}
}
last++;
}
return jsvLockAgain(parent);
}
/** recursive reverse, because we're dealing with a linked list that
* MAY only be linked in one direction (eg. string/arraybuffer).
*/
void _jswrap_array_reverse_block(JsVar *parent, JsvIterator *it, int items) {
assert(items > 1);
JsvIterator ita = jsvIteratorClone(it);
JsvIterator itb = jsvIteratorClone(it);
// move second pointer halfway through (round up)
int i;
for (i=(items+1)/2;i>0;i--)
jsvIteratorNext(&itb);
// recurse if >3 items. If 3 we can cope with it here
if (items > 3) {
_jswrap_array_reverse_block(parent, &ita, items/2);
_jswrap_array_reverse_block(parent, &itb, items/2);
}
// start flipping values (round down for how many)
for (i=items/2;i>0;i--) {
JsVar *va = jsvIteratorGetValue(&ita);
JsVar *vb = jsvIteratorGetValue(&itb);
jsvIteratorSetValue(&ita, vb);
jsvIteratorSetValue(&itb, va);
jsvUnLock(va);
jsvUnLock(vb);
// if it's an array, we need to swap the key values too
if (jsvIsArray(parent)) {
JsVar *ka = jsvIteratorGetKey(&ita);
JsVar *kb = jsvIteratorGetKey(&itb);
JsVarInt kva = jsvGetInteger(ka);
JsVarInt kvb = jsvGetInteger(kb);
jsvSetInteger(ka, kvb);
jsvSetInteger(kb, kva);
jsvUnLock(ka);
jsvUnLock(kb);
}
jsvIteratorNext(&ita);
jsvIteratorNext(&itb);
}
// now recurse!
jsvIteratorFree(&ita);
jsvIteratorFree(&itb);
}
/*JSON{
"type" : "method",
"class" : "Array",
"name" : "reverse",
"ifndef" : "SAVE_ON_FLASH",
"generate" : "jswrap_array_reverse",
"return" : ["JsVar","The array, but reversed."]
}
Reverse all elements in this array (in place)
*/
JsVar *jswrap_array_reverse(JsVar *parent) {
if (!jsvIsIterable(parent) || jsvIsObject(parent)) return 0;
int len = 0;
if (jsvIsArray(parent)) {
/* arrays are sparse, so we must handle them differently.
* We work out how many NUMERIC keys they have, and we
* reverse only those. Then, we reverse the key values too */
JsvIterator it;
jsvIteratorNew(&it, parent);
while (jsvIteratorHasElement(&it)) {
JsVar *k = jsvIteratorGetKey(&it);
if (jsvIsInt(k)) len++;
jsvUnLock(k);
jsvIteratorNext(&it);
}
jsvIteratorFree(&it);
} else
len = jsvGetLength(parent);
JsvIterator it;
jsvIteratorNew(&it, parent);
if (len>1) {
_jswrap_array_reverse_block(parent, &it, len);
}
// if it's an array, we must change the values on the keys
if (jsvIsArray(parent)) {
JsVarInt last = jsvGetArrayLength(parent)-1;
while (jsvIteratorHasElement(&it)) {
JsVar *k = jsvIteratorGetKey(&it);
jsvSetInteger(k, last-jsvGetInteger(k));
jsvUnLock(k);
jsvIteratorNext(&it);
}
}
jsvIteratorFree(&it);
return jsvLockAgain(parent);
}