-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
1704 lines (1305 loc) · 38.6 KB
/
index.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
// Core set of functions that are available. If it's not here, it
// is not supported.
// NOTE: these functions are mostly reduction functions over a list
// which I feel is absolutely amusing. One of the many things
// that are amazing about a list.
// NOTE:
// could've used variadic functions too. But yeah, I just wanted
// to use the arguments object for fun and also that lisp-y wants
// run in a lot more environments...like one's before the ES6 and
// so yeah I thought this would help
// NOTE: These functions are modeled after the clojure functions
// NOTE: What I also realized recently was that, the list functions
// almost always return a JS Array, which sits perfectly well into
// our AST, because our AST is also one. I'm not sure if this is the
// right way to do things. Help me out here?
const utils = require("./utils");
const fs = require("fs");
const path = require("path");
const throwArgsError = require("../error").throwArgsError;
const throwError = require("../error").throwError;
const storeImports = require("../store");
const getArgs = utils.getArgs;
const isZero = utils.isZero;
const sequenceIterator = utils.sequenceIterator;
const { dispatchers, dispatch, getState } = storeImports;
// Returns the sum of numbers
function add() {
const [args, argsCount] = getArgs(arguments);
if (argsCount === 0) {
return 0;
}
return args.reduce((total, number) => total + number, 0);
}
// Returns the difference of numbers
function subtract() {
const [args, argsCount] = getArgs(arguments);
if (argsCount === 0) {
return 0;
}
if (args.length === 1) {
return -1 * args[0];
}
if (args.length === 2) {
const [x, y] = args;
return x - y;
}
const [startValue, ...toSubtractList] = args;
return toSubtractList.reduce(
(total, number) => subtract(total, number),
startValue
);
}
// Returns the product of numbers
function multiply() {
const [args, argsCount] = getArgs(arguments);
if (argsCount === 0) {
return 1;
}
return args.reduce((total, number) => total * number, 1);
}
// Returns the quotient of numbers
function divide() {
const [args, argsCount] = getArgs(arguments);
if (argsCount === 0) {
throwArgsError("divide", argsCount, 1);
return;
}
if (args.length === 1) {
// show error if it is 0
isZero(args[0]);
return 1 / args[0];
}
if (args.length === 2) {
const [x, y] = args;
// Show error if it is 0
isZero(y);
return x / y;
}
// NOTE: divide(/) in clojure gives the fraction if the
// numbers are not perfectly divisible.
// TODO: Try to emulate clojure divide function, in the sense that
// I must display the fraction rep. by default
const [startNumber, ...restArgs] = args;
return restArgs.reduce((total, number) => {
// Show error if it is 0
isZero(number);
return divide(total, number);
}, startNumber);
}
// Returns modulus of num & div
function mod() {
const [args, argsCount] = getArgs(arguments);
if (argsCount !== 2) {
throwArgsError("mod", argsCount, 2);
return;
}
const [num, div] = args;
if (!div) {
throwError({
func: "mod",
message: "div is not valid",
});
return;
}
return num % div;
}
// Returns a number one greater than num
function inc() {
const [args, argsCount] = getArgs(arguments);
if (argsCount !== 1) {
throwArgsError("inc", argsCount, 1);
return;
}
const num = args[0];
if (typeof num !== "number") {
throwError({ func: "inc", message: "expected a number!" });
return;
}
// Or could have used the add function, like so: return add(num, 1)
return num + 1;
}
// Returns a number one less than num
function dec() {
const [args, argsCount] = getArgs(arguments);
if (argsCount !== 1) {
throwArgsError("dec", argsCount, 1);
return;
}
const num = args[0];
return num - 1;
}
// NOTE: we might have to add support for the types but yes,
// this is a lisp within javascript-land. So yeah, let it be.
// Returns a list of xs
function list() {
const [args] = getArgs(arguments);
return args;
}
// Returns the first item in the collection
function first() {
const [args, argsCount] = getArgs(arguments);
// NOTE: It'll be good to check if it is an array/list as well
if (argsCount !== 1) {
// NOTE: I'm doing this because I think it would help
// for something like prop-types to exist for node
// projects and this object representation atleast
// would help in the documentation process. And this
// applies to all the functions that are applied to collections.
throwArgsError("first", argsCount, 1);
return;
}
const coll = args[0];
const [first, ...rest] = coll;
return first;
}
// Returns the last element from a collection
function last() {
const [args, argsCount] = getArgs(arguments);
if (argsCount !== 1) {
throwArgsError("last", argsCount, 1);
return;
}
const coll = args[0];
const collLength = args.length;
return coll[collLength - 1];
}
// Returns the sorted collection in ascending order
// Can use in combination with `reverse` to get the descending order
function sort() {
const [args, argsCount] = getArgs(arguments);
if (argsCount !== 1) {
throwArgsError("sort", argsCount, 1);
return;
}
const coll = args[0];
// return the first element of the collection
// TODO: try and implement the function my self, to
// help add performance gains.
// GOTCHA: sort function sorts the list lexicographically.
coll.sort((a, b) => a - b);
return coll;
}
// Returns all elements after the first
function rest() {
const [args, argsCount] = getArgs(arguments);
if (argsCount !== 1) {
throwArgsError("rest", argsCount, 1);
return;
}
const coll = args[0];
const [first, ...rest] = coll;
return rest;
}
// Concats all argument strings together
function str() {
const [args, argsCount] = getArgs(arguments);
if (!argsCount) {
return "";
}
return args.reduce(
(accString, currentString) => accString.concat(currentString),
""
);
}
// TODO: This function should work for all types
// Inserts a character in between the different words that are passed
// while concat-ing them in the process
function interpose() {
const [args, argsCount] = getArgs(arguments);
if (argsCount !== 2) {
throwArgsError("interpose", argsCount, 2);
return;
}
// FIXME: "\"" The double quote can't be passed, unless it is escaped,
// or else it goes into an infinite loop
const [char, wordList] = args;
const [startWord, ...restWordList] = wordList;
const wordListLen = wordList.length;
return restWordList.reduce((accStr, currentWord, index) => {
if (index === wordListLen - 1) {
return accStr;
}
return accStr.concat(char, currentWord);
}, startWord);
}
// Returns a collection in the reverse order
function reverse() {
const [args, argsCount] = getArgs(arguments);
if (argsCount !== 1) {
throwArgsError("reverse", argsCount, 1);
return;
}
const list = args[0];
return list.reverse();
}
// Returns a collection of numbers from start, until stop
// increments are in step (default 1)
function range() {
const [args, argsCount] = getArgs(arguments);
let start = 0,
end,
step = 1;
if (argsCount <= 0 || argsCount > 3) {
throwArgsError("range", argsCount, 1);
return;
}
if (argsCount === 1) {
end = args[0];
}
if (argsCount === 2) {
start = args[0];
end = args[1];
}
if (argsCount === 3) {
start = args[0];
end = args[1];
step = args[2];
}
// get result from the iterator
let result = [];
let numberSeq = sequenceIterator(start, end, step);
for (let num of numberSeq) {
result.push(num);
}
return result;
}
// shuffles the elements of a list
// uses the Fisher-Yates Shuffle Algorithm to perform the shuffle
// This was taken right off of Mike Bostock's post : https://bost.ocks.org/mike/shuffle/
function shuffle() {
const [args, argsCount] = getArgs(arguments);
if (argsCount !== 1) {
throwArgsError("shuffle", argsCount, 1);
return;
}
let listCopy = args[0];
// NOTE: The algorithm is an in-place shuffling algorithm
// I'm really sorry about the variable names if you don't use
// autocomplete. This sentence was composed mainly by autocomplete.
let marker = listCopy.length,
temp,
intermediate;
while (marker) {
intermediate = Math.floor(Math.random() * marker--);
temp = listCopy[marker];
listCopy[marker] = listCopy[intermediate];
listCopy[intermediate] = temp;
}
return listCopy;
}
// Returns the sum of collection of numbers
function sum() {
const [args, argsCount] = getArgs(arguments);
if (argsCount !== 1) {
throwArgsError("sum", argsCount, 1);
return;
}
const list = args[0];
return add(...list);
}
// Returns the product of all elements of collection
function product() {
const [args, argsCount] = getArgs(arguments);
if (argsCount !== 1) {
throwArgsError("product", argsCount, 1);
return;
}
const list = args[0];
return multiply(...list);
}
// The infamous map function, supply a predicate and list.
function map() {
const [args, argsCount] = getArgs(arguments);
if (argsCount !== 2) {
throwArgsError("map", argsCount, 2);
return;
}
const [funcToApply, list] = args;
return list.map(elem => {
// TODO: might have to do some checks perhaps? this will
// come after additional information is supplied
// by the AST
return funcToApply(elem);
});
}
// interleave does what zip does in Haskell
// `interleaves` multiple lists until one of them is exhausted
// NOTE: Pass only lists as arguments
function interleave() {
const [args, argsCount] = getArgs(arguments);
if (argsCount === 1) {
const list = args[0];
return list;
}
if (argsCount === 0) {
return [];
}
const lists = args;
const listsLengths = lists.map(xs => xs.length);
let numOfIterations = sort(listsLengths)[0];
let finalResult = [];
while (numOfIterations) {
lists.forEach(list => {
const currentElement = list.shift();
finalResult.push(currentElement);
});
numOfIterations--;
}
return finalResult;
}
// Returns a new list with the values that are being
// appended to the list or conj[oined] to the list.
function conj() {
const [args, argsCount] = getArgs(arguments);
if (argsCount !== 2) {
throwArgsError("conj", argsCount, 1);
return;
}
const [originalList, ...newElements] = args;
return newElements.reduce(
(resList, currentElement) => [...resList, currentElement],
originalList
);
}
// Returns a new list with an element added to the beginning
// of the list provided to this function
function cons() {
const [args, argsCount] = getArgs(arguments);
if (argsCount !== 2) {
throwArgsError("cons", argsCount, 2);
return;
}
const [x, coll] = args;
return [x, ...coll];
}
// Returns the length of a list
function count() {
const [args, argsCount] = getArgs(arguments);
if (argsCount !== 1) {
throwArgsError("count", argsCount, 1);
return;
}
const list = args[0];
return list.length;
}
// Checks whether a number is even
function isEven() {
const [args, argsCount] = getArgs(arguments);
if (argsCount !== 1) {
throwArgsError("isEven", argsCount, 1);
return;
}
const number = args[0];
return number % 2 === 0;
}
// Checks if the number is odd
function isOdd() {
const [args, argsCount] = getArgs(arguments);
if (argsCount !== 1) {
throwArgsError("isOdd", argsCount, 1);
return;
}
return !isEven(args);
}
// Returns true if number is > 0
function isPos() {
const [args, argsCount] = getArgs(arguments);
if (argsCount !== 1) {
throwArgsError("isPos", argsCount, 1);
return;
}
const num = args[0];
return num > 0;
}
// Returns true if number is < 0
function isNeg() {
const [args, argsCount] = getArgs(arguments);
if (argsCount !== 1) {
throwArgsError("isNeg", argsCount, 1);
return;
}
const num = args[0];
return num < 0;
}
// Checks if substring is present in the string
function includes() {
const [args, argsCount] = getArgs(arguments);
if (argsCount !== 2) {
throwArgsError("includes", argsCount, 2);
return;
}
const [str, substr] = args;
// NOTE: Using indexOf over includes
return str.indexOf(substr) !== -1;
}
// Converts the first letter of the string to upper-case
// and the rest of the characters to lower-case
function capitalize() {
const [args, argsCount] = getArgs(arguments);
if (argsCount !== 1) {
throwArgsError("capitalize", argsCount, 1);
return;
}
const str = args[0];
const strSplit = str.split("");
// NOTE: This process can be performed with simple
// joins and then applying toUpperCase and toLowerCase
// on those parts separately.
return strSplit.reduce((capWord, letter, index) => {
if (index === 0) {
return capWord.concat(letter.toUpperCase());
}
return capWord.concat(letter.toLowerCase());
}, "");
}
// the infamous `filter` reduction function
function filter() {
const [args, argsCount] = getArgs(arguments);
if (argsCount !== 2) {
throwArgsError("filter", argsCount, 2);
return;
}
const [funcToApply, list] = args;
return list.filter(elem => funcToApply(elem));
}
// assoc[ciate] method is used to `cons` a key-value pair onto
// a given map
// TODO: as of now, only string keys can be added with assoc.
// otherwise it keeps going into this, infinite loop if the
// colon is used.
function assoc() {
const [args, argsCount] = getArgs(arguments);
if (argsCount <= 1) {
throwArgsError("assoc", argsCount, 2);
return;
}
const [originalObj, ...keyValues] = args;
const resObj = originalObj;
// TODO: to get more data from the AST, to check whether `originalObj`
// is a proper object or not
if (keyValues.length % 2 !== 0) {
// The keys and values aren't appropriate
throwError({
func: "assoc",
message: "Key Value pairs are incorrect",
});
return;
}
// TODO: check whether the proper syntax is used to define the keys
// and the values. This will be easier if at the very least that part
// of the parser is separated out.
for (let iter = 0; iter < keyValues.length; iter += 2) {
// odd indices are values and even indices are keys
const currentValue = keyValues[iter];
resObj[currentValue] = keyValues[iter + 1];
}
return resObj;
}
// dissoc - dissassociates certain keys from a given map
function dissoc() {
const [args, argsCount] = getArgs(arguments);
if (argsCount <= 1) {
throwArgsError("dissoc", argsCount, 2);
return;
}
const [originalObj, ...setOfKeys] = args;
return Object.keys(originalObj).reduce((resObj, currentKey) => {
if (setOfKeys.indexOf(currentKey) !== -1) {
return resObj;
}
return { ...resObj, [currentKey]: originalObj[currentKey] };
}, {});
}
// Returns merging lists together
function concat() {
const [args, argsCount] = getArgs(arguments);
if (argsCount < 1) {
throwArgsError("concat", argsCount, 1);
return;
}
const [originalList, ...concatColls] = args;
return concatColls.reduce(
(concatedList, currentColl) => {
// Check if it is a valid list
if (!Array.isArray(currentColl)) {
throwError({
func: "concat",
message: "Incorrect argument passed!",
});
return;
}
return [...concatedList, ...currentColl];
},
[...originalList]
);
}
// Returns a new list with the duplicates removed
function distinct() {
const [args, argsCount] = getArgs(arguments);
if (argsCount !== 1) {
throwArgsError("distinct", argsCount, 1);
return;
}
const coll = args[0];
return [...new Set(coll)];
}
// returns a single, flat list by taking a nested list as input
function flatten() {
const [args, argsCount] = getArgs(arguments);
if (argsCount !== 1) {
throwArgsError("flatten", argsCount, 1);
return;
}
const originalList = args[0];
function flattenHelper(list) {
return list.reduce((flatList, currentElement) => {
if (Array.isArray(currentElement)) {
return [...flatList, ...flattenHelper(currentElement)];
}
return [...flatList, currentElement];
}, []);
}
return flattenHelper(originalList);
}
// Returns an object with the count of each unique element in the collection
function frequencies() {
const [args, argsCount] = getArgs(arguments);
if (argsCount !== 1) {
throwArgsError("frequencies", argsCount, 1);
return;
}
const originalList = args[0];
return originalList.reduce((freqObj, currentElement) => {
if (!freqObj[currentElement]) {
return { ...freqObj, [currentElement]: 1 };
}
return { ...freqObj, [currentElement]: freqObj[currentElement] + 1 };
}, {});
}
// Returns the greatest of the numbers passed
function max() {
const [args, argsCount] = getArgs(arguments);
if (argsCount < 1) {
throwArgsError("max", argsCount, 1);
return;
}
const listOfNumbers = args;
const sortedList = listOfNumbers.sort((a, b) => a - b);
const reverseList = sortedList.reverse();
const greatest = reverseList[0];
return greatest;
}
// Returns the minimum of the numbers passed
function min() {
const [args, argsCount] = getArgs(arguments);
if (argsCount < 1) {
throwArgsError("min", argsCount, 1);
return;
}
const listOfNumbers = args;
const sortedList = listOfNumbers.sort((a, b) => a - b);
const smallest = sortedList[0];
return smallest;
}
function nth() {
const [args, argsCount] = getArgs(arguments);
if (argsCount !== 2) {
throwArgsError("nth", argsCount, 2);
return;
}
const [coll, index] = args;
// Handle error state
if (!coll[index]) {
throwError({
func: "nth",
message: "Index out of bounds",
});
return;
}
return coll[index];
}
// Returns random float value between 0 (inclusive) and n (default 1) (exclusive)
function rand() {
const [args, argsCount] = getArgs(arguments);
if (argsCount > 1) {
throwArgsError("rand", argsCount, 1);
return;
}
const n = argsCount ? args[0] : 1;
return Math.random() * n;
}
// Returns random integer value between 0 (
function randInt() {
// NOTE: For some reason, the node REPL would stop
// if I used the name of the function to be rand_int
// although it is a valid function name
// A similar problem happens when I use :'s in the code
const [args, argsCount] = getArgs(arguments);
if (argsCount !== 1) {
throwArgsError("randInt", argsCount, 1);
return;
}
const n = args[0];
return Math.floor(Math.random() * n);
}
// Returns a random element from a collection
function randNth() {
const [args, argsCount] = getArgs(arguments);
if (argsCount !== 1) {
throwArgsError("randNth", argsCount, 1);
return;
}
const coll = args[0];
const collLength = coll.length;
const randomIndex = randInt(collLength);
return coll[randomIndex];
}
// Returns a sequence of xs
function repeat() {
const [args, argsCount] = getArgs(arguments);
if (argsCount !== 2) {
throwArgsError("repeat", argsCount, 2);
return;
}
// NOTE: No Lazy Sequences available as of yet,
// therefore I'm not working on the only x as
// argument case
// TODO: Handle the only x case as described above
const [n, x] = args;
let resultList = [];
let counter = 0;
while (counter < n) {
resultList.push(x);
counter++;
}
return resultList;
}
// Prints values
function print() {
const [args, argsCount] = getArgs(arguments);
if (argsCount === 0) {
return;
}
console.log("\n", ...args);
// To sort off match the clojure REPL
return null;
}
// Returns the collection rotated by x positions
function rotate() {
const [args, argsCount] = getArgs(arguments);
if (argsCount !== 2) {
throwArgsError("rotate", argsCount, 2);
return;
}
const [x, coll] = args;
if (x === 0) {
return coll;
}
let list = [];
let listLen = coll.length;
coll.forEach((currentElement, currentIndex) => {
let updatedIndex;
if (x < 0) {
updatedIndex = (currentIndex + (listLen - x) - 1) % listLen;
} else {
updatedIndex = (currentIndex + x - 1) % listLen;
}
list[updatedIndex] = currentElement;
});
return list;
}
// Within clojure-land, this method is known as a
// special form. As of now, unbounds are not supported.
// TODO: Add support for docstrings, but for that a
// docs function must exist.
// This method saves a varaible with a global scope
function def() {
const [args, argsCount] = getArgs(arguments);
if (argsCount !== 2) {
throwArgsError("def", argsCount, 2);
return;
}
const [varName, value] = args;
// obtaining the dispatch object from the
// action creators
const actionObject = dispatchers.updateVar(varName, value);
// dispatching the action
dispatch(actionObject);
// to make it similar to the Clojure REPL
const result = `#user/${varName}`;
return result;
}
// This method is similar to a let binding. The
// problem in naming the method as let is that it
// is already a keyword within JS. Hence ldef.
function ldef() {
const [args, argsCount] = getArgs(arguments);
if (argsCount !== 2) {
throwArgsError("ldef", argsCount, 2);
return;
}
const [bindings, expression] = args;
const currentState = getState();
let currentLocalVars = [];