-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunk.lua
More file actions
1851 lines (1723 loc) · 69.7 KB
/
funk.lua
File metadata and controls
1851 lines (1723 loc) · 69.7 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
-- =============================================================================
-- funk.lua — Functional programming utilities for TurtleWoW / Lua 5.0
-- =============================================================================
-- Inspired by:
-- • underscore.lua https://github.com/mirven/underscore.lua
-- • lodash https://lodash.com/docs
-- • ramda https://ramdajs.com/docs
--
-- TARGET: Lua 5.0 / World of Warcraft (TurtleWoW) add-on environment.
--
-- ┌──────────────────────── JS ↔ Lua quick-reference ────────────────────────┐
-- │ CONCEPT │ JavaScript │ Lua │
-- │──────────────────────┼─────────────────────────┼──────────────────────── │
-- │ Array index │ 0-based arr[0] │ 1-based arr[1] │
-- │ Undefined / null │ undefined / null │ nil │
-- │ Length │ arr.length │ table.getn(arr) │
-- │ String concat │ "a" + "b" │ "a" .. "b" │
-- │ Arrow func │ (x) => x * 2 │ function(x) return x*2 end│
-- │ Spread │ fn(...args) │ fn(unpack(args)) │
-- │ Destructure │ const [a,b] = arr │ local a,b = arr[1],arr[2]│
-- │ for-of │ for (const v of arr) │ for _,v in ipairs(arr) │
-- │ Object literal │ { key: value } │ { key = value } │
-- │ typeof │ typeof x │ type(x) │
-- │ true equality │ === │ == (Lua has no ===) │
-- │ Ternary │ cond ? a : b │ cond and a or b │
-- └──────────────────────────────────────────────────────────────────────────┘
--
-- USAGE (WoW 1.12 / Lua 5.0 .toc addon):
-- local F = FunkDemo.funk -- populated by funk.lua when loaded earlier in .toc
--
-- USAGE (standalone / dofile):
-- local F = dofile("funk.lua") -- return value is the funk table
--
-- F.map({1,2,3}, function(x) return x * 2 end) --> {2, 4, 6}
-- F.filter({1,2,3,4}, function(x) return math.mod(x, 2) == 0 end) --> {2, 4}
-- F.reduce({1,2,3,4}, 0, function(acc, x) return acc + x end) --> 10
-- =============================================================================
-- WoW 1.12 / Lua 5.0: declare the per-addon namespace as a single global table.
-- Every file in the addon reads/writes this same table instead of _G directly.
-- When loaded via dofile() standalone the table is still created here.
FunkDemo = FunkDemo or {}
local _ns = FunkDemo
local funk = {}
-- ---------------------------------------------------------------------------
-- Internal helpers
-- ---------------------------------------------------------------------------
-- _iter: returns a closure-based iterator over a plain table *or* passes
-- through an already-callable iterator function.
-- In JS terms: converts an Array or Iterable into an iterator.
-- NOTE: uses a simple closure instead of coroutine.wrap because the
-- coroutine library is not available in the WoW 1.12 Lua sandbox.
local function _iter(list_or_iter)
if type(list_or_iter) == "function" then
return list_or_iter
end
if list_or_iter == nil then
return function() return nil end
end
local i = 0
local n = table.getn(list_or_iter)
return function()
i = i + 1
if i <= n then return list_or_iter[i] end
end
end
-- _identity: returns its argument unchanged (lodash _.identity / ramda R.identity).
local function _identity(x)
return x
end
-- _noop: does nothing (lodash _.noop).
local function _noop() end
-- _toarray: collect an iterator into a plain array table.
local function _toarray(list)
if type(list) == "table" then return list end
local arr = {}
for v in list do
arr[table.getn(arr) + 1] = v
end
return arr
end
-- ---------------------------------------------------------------------------
-- ═══════════════════════════════════════════════════════════════════════════
-- SECTION 1 — COLLECTION FUNCTIONS
-- Operate on arrays (sequential tables, 1-indexed) and iterator functions.
-- ═══════════════════════════════════════════════════════════════════════════
-- ---------------------------------------------------------------------------
-- -----------------------------------------------------------------------------
-- funk.each(list, iteratee)
-- lodash: _.forEach ramda: R.forEach
-- JS equivalent: arr.forEach(fn)
--
-- Calls `iteratee(value)` for every element.
-- Returns the original list unchanged (side-effects only).
-- Note: Lua has no implicit `this`; the element is always the first argument.
-- -----------------------------------------------------------------------------
function funk.each(list, iteratee)
for v in _iter(list) do
iteratee(v)
end
return list
end
funk.forEach = funk.each
funk.for_each = funk.each
-- -----------------------------------------------------------------------------
-- funk.eachWithIndex(list, iteratee)
-- lodash: _.forEach (callback receives value, index)
-- JS equivalent: arr.forEach((v, i) => ...)
--
-- Calls `iteratee(value, index)` — index is 1-based in Lua.
-- -----------------------------------------------------------------------------
function funk.eachWithIndex(list, iteratee)
local arr = _toarray(list)
for i = 1, table.getn(arr) do
iteratee(arr[i], i)
end
return arr
end
-- -----------------------------------------------------------------------------
-- funk.map(list, iteratee)
-- lodash: _.map ramda: R.map
-- JS equivalent: arr.map(fn)
--
-- Returns a *new* table where each element is the result of iteratee(value).
-- The original list is never modified (pure function, like ramda).
-- -----------------------------------------------------------------------------
function funk.map(list, iteratee)
local result = {}
for v in _iter(list) do
result[table.getn(result) + 1] = iteratee(v)
end
return result
end
funk.collect = funk.map
-- -----------------------------------------------------------------------------
-- funk.mapWithIndex(list, iteratee)
-- lodash: _.map (callback receives value, index)
-- JS equivalent: arr.map((v, i) => ...)
-- -----------------------------------------------------------------------------
function funk.mapWithIndex(list, iteratee)
local arr = _toarray(list)
local result = {}
for i = 1, table.getn(arr) do
result[i] = iteratee(arr[i], i)
end
return result
end
-- -----------------------------------------------------------------------------
-- funk.reduce(list, accumulator, iteratee)
-- lodash: _.reduce ramda: R.reduce
-- JS equivalent: arr.reduce(fn, initialValue)
--
-- Note the argument ORDER DIFFERENCE from JS:
-- JS: arr.reduce((acc, val) => ..., initial)
-- Lua: funk.reduce(arr, initial, function(acc, val) ... end)
-- The accumulator/memo is the SECOND argument here, not inside the callback.
-- -----------------------------------------------------------------------------
function funk.reduce(list, accumulator, iteratee)
local memo = accumulator
for v in _iter(list) do
memo = iteratee(memo, v)
end
return memo
end
funk.foldl = funk.reduce
funk.inject = funk.reduce
-- -----------------------------------------------------------------------------
-- funk.reduceRight(list, accumulator, iteratee)
-- lodash: _.reduceRight ramda: R.reduceRight
-- JS equivalent: arr.reduceRight(fn, initialValue)
--
-- Iterates from the last element to the first.
-- -----------------------------------------------------------------------------
function funk.reduceRight(list, accumulator, iteratee)
local arr = _toarray(list)
local memo = accumulator
for i = table.getn(arr), 1, -1 do
memo = iteratee(memo, arr[i])
end
return memo
end
funk.foldr = funk.reduceRight
-- -----------------------------------------------------------------------------
-- funk.filter(list, predicate)
-- lodash: _.filter ramda: R.filter
-- JS equivalent: arr.filter(fn)
--
-- Returns a new table with only the elements for which predicate returns truthy.
-- Lua truthy: anything except `false` and `nil`. 0 and "" ARE truthy in Lua!
-- (Different from JavaScript where 0 and "" are falsy.)
-- -----------------------------------------------------------------------------
function funk.filter(list, predicate)
local result = {}
for v in _iter(list) do
if predicate(v) then
result[table.getn(result) + 1] = v
end
end
return result
end
funk.select = funk.filter
-- -----------------------------------------------------------------------------
-- funk.reject(list, predicate)
-- lodash: _.reject ramda: R.reject
-- JS equivalent: arr.filter(v => !fn(v))
--
-- Opposite of filter — keeps elements for which predicate returns falsy.
-- -----------------------------------------------------------------------------
function funk.reject(list, predicate)
local result = {}
for v in _iter(list) do
if not predicate(v) then
result[table.getn(result) + 1] = v
end
end
return result
end
-- -----------------------------------------------------------------------------
-- funk.find(list, predicate)
-- lodash: _.find ramda: R.find
-- JS equivalent: arr.find(fn)
--
-- Returns the *first* element for which predicate is truthy, or nil.
-- JS returns `undefined` when nothing matches; Lua returns `nil`.
-- -----------------------------------------------------------------------------
function funk.find(list, predicate)
for v in _iter(list) do
if predicate(v) then return v end
end
return nil
end
funk.detect = funk.find
-- -----------------------------------------------------------------------------
-- funk.findIndex(list, predicate)
-- lodash: _.findIndex
-- JS equivalent: arr.findIndex(fn)
--
-- Returns the 1-based index of the first matching element, or -1.
-- JS returns -1 when not found; this matches that convention.
-- -----------------------------------------------------------------------------
function funk.findIndex(list, predicate)
local arr = _toarray(list)
for i = 1, table.getn(arr) do
if predicate(arr[i]) then return i end
end
return -1
end
-- -----------------------------------------------------------------------------
-- funk.every(list, predicate)
-- lodash: _.every ramda: R.all
-- JS equivalent: arr.every(fn)
--
-- Returns true only if predicate returns truthy for ALL elements.
-- Returns true for an empty list (vacuous truth — same as JS).
-- -----------------------------------------------------------------------------
function funk.every(list, predicate)
predicate = predicate or _identity
for v in _iter(list) do
if not predicate(v) then return false end
end
return true
end
funk.all = funk.every
-- -----------------------------------------------------------------------------
-- funk.some(list, predicate)
-- lodash: _.some ramda: R.any
-- JS equivalent: arr.some(fn)
--
-- Returns true if predicate returns truthy for AT LEAST ONE element.
-- Returns false for an empty list (same as JS).
-- -----------------------------------------------------------------------------
function funk.some(list, predicate)
predicate = predicate or _identity
for v in _iter(list) do
if predicate(v) then return true end
end
return false
end
funk.any = funk.some
-- -----------------------------------------------------------------------------
-- funk.includes(list, value)
-- lodash: _.includes ramda: R.includes
-- JS equivalent: arr.includes(value)
--
-- Returns true if `value` appears in the list (uses == equality).
-- Lua has no strict equality (===); == is used for all types.
-- -----------------------------------------------------------------------------
function funk.includes(list, value)
for v in _iter(list) do
if v == value then return true end
end
return false
end
funk.include = funk.includes
funk.contains = funk.includes
-- -----------------------------------------------------------------------------
-- funk.pluck(list, key)
-- lodash: _.map(list, key) ramda: R.pluck
-- JS equivalent: arr.map(obj => obj[key])
--
-- Extracts a named property from every element in the list.
-- -----------------------------------------------------------------------------
function funk.pluck(list, key)
return funk.map(list, function(v)
if v == nil then return nil end
return v[key]
end)
end
-- -----------------------------------------------------------------------------
-- funk.invoke(list, methodName, ...)
-- lodash: _.invokeMap
-- JS equivalent: arr.forEach(obj => obj[method](...args))
--
-- Calls the named method on every element, passing extra args.
-- In Lua you must pass the object itself as first arg: obj:method(...)
-- -----------------------------------------------------------------------------
function funk.invoke(list, methodName, ...)
local args = arg
funk.each(list, function(obj)
if obj ~= nil and obj[methodName] ~= nil then
obj[methodName](obj, unpack(args))
end
end)
return list
end
-- -----------------------------------------------------------------------------
-- funk.groupBy(list, iteratee)
-- lodash: _.groupBy ramda: R.groupBy
-- JS equivalent: _.groupBy(arr, fn) (lodash syntax closest)
--
-- Returns a table whose keys are the results of iteratee and values are arrays
-- of elements that produced that key.
-- iteratee can be a function OR a string key name.
-- -----------------------------------------------------------------------------
function funk.groupBy(list, iteratee)
local fn = type(iteratee) == "function" and iteratee
or function(v) if v == nil then return nil end return v[iteratee] end
local result = {}
for v in _iter(list) do
local k = fn(v)
if result[k] == nil then result[k] = {} end
result[k][table.getn(result[k]) + 1] = v
end
return result
end
-- -----------------------------------------------------------------------------
-- funk.countBy(list, iteratee)
-- lodash: _.countBy
-- JS equivalent: _.countBy(arr, fn)
--
-- Like groupBy but returns counts instead of arrays.
-- -----------------------------------------------------------------------------
function funk.countBy(list, iteratee)
local fn = type(iteratee) == "function" and iteratee
or function(v) if v == nil then return nil end return v[iteratee] end
local result = {}
for v in _iter(list) do
local k = fn(v)
result[k] = (result[k] or 0) + 1
end
return result
end
-- -----------------------------------------------------------------------------
-- funk.partition(list, predicate)
-- lodash: _.partition ramda: R.partition
-- JS equivalent: [arr.filter(fn), arr.filter(v => !fn(v))]
--
-- Returns TWO tables: { matching, nonMatching }.
-- Note: Lua returns multiple values; use:
-- local yes, no = unpack(funk.partition(arr, fn))
-- -----------------------------------------------------------------------------
function funk.partition(list, predicate)
local yes, no = {}, {}
for v in _iter(list) do
if predicate(v) then
yes[table.getn(yes) + 1] = v
else
no[table.getn(no) + 1] = v
end
end
return {yes, no}
end
-- -----------------------------------------------------------------------------
-- funk.sortBy(list, iteratee)
-- lodash: _.sortBy ramda: R.sortBy
-- JS equivalent: [...arr].sort((a,b) => fn(a) < fn(b) ? -1 : 1)
--
-- Returns a new sorted array. iteratee can be a function or a string key.
-- Lua's table.sort is an in-place unstable sort; we copy first to stay pure.
-- -----------------------------------------------------------------------------
function funk.sortBy(list, iteratee)
local fn = type(iteratee) == "function" and iteratee
or function(v) if v == nil then return nil end return v[iteratee] end
local arr = {}
for v in _iter(list) do arr[table.getn(arr) + 1] = v end
table.sort(arr, function(a, b) return fn(a) < fn(b) end)
return arr
end
-- -----------------------------------------------------------------------------
-- funk.sort(list, comparator)
-- lodash: _.sortBy (with explicit comparator)
-- JS equivalent: [...arr].sort(comparator)
--
-- Returns a new sorted copy using the raw comparator function.
-- Comparator must return true when a should come before b (like JS's < 0).
-- Note: JS comparators return a number; Lua comparators return a boolean.
-- -----------------------------------------------------------------------------
function funk.sort(list, comparator)
local arr = {}
for v in _iter(list) do arr[table.getn(arr) + 1] = v end
table.sort(arr, comparator)
return arr
end
-- -----------------------------------------------------------------------------
-- funk.min(list, iteratee) / funk.max(list, iteratee)
-- lodash: _.minBy / _.maxBy ramda: R.minBy / R.maxBy
-- JS equivalent: arr.reduce((min, v) => fn(v) < fn(min) ? v : min)
--
-- Returns the element (not the value) with the smallest/largest computed score.
-- iteratee defaults to identity so plain number arrays work without a function.
-- -----------------------------------------------------------------------------
function funk.min(list, iteratee)
local fn = iteratee or _identity
return funk.reduce(list, {item = nil, score = nil}, function(acc, v)
local s = fn(v)
if acc.item == nil or s < acc.score then
return {item = v, score = s}
end
return acc
end).item
end
function funk.max(list, iteratee)
local fn = iteratee or _identity
return funk.reduce(list, {item = nil, score = nil}, function(acc, v)
local s = fn(v)
if acc.item == nil or s > acc.score then
return {item = v, score = s}
end
return acc
end).item
end
-- -----------------------------------------------------------------------------
-- funk.sum(list, iteratee)
-- lodash: _.sumBy
-- JS equivalent: arr.reduce((s, v) => s + fn(v), 0)
-- -----------------------------------------------------------------------------
function funk.sum(list, iteratee)
local fn = iteratee or _identity
return funk.reduce(list, 0, function(acc, v) return acc + fn(v) end)
end
-- -----------------------------------------------------------------------------
-- funk.mean(list, iteratee)
-- lodash: _.meanBy
-- JS equivalent: arr.reduce(...) / arr.length
-- -----------------------------------------------------------------------------
function funk.mean(list, iteratee)
local arr = _toarray(list)
if table.getn(arr) == 0 then return 0 end
return funk.sum(arr, iteratee) / table.getn(arr)
end
funk.average = funk.mean
-- ---------------------------------------------------------------------------
-- ═══════════════════════════════════════════════════════════════════════════
-- SECTION 2 — ARRAY FUNCTIONS
-- Functions specific to sequential (integer-keyed, 1-based) tables.
-- ═══════════════════════════════════════════════════════════════════════════
-- ---------------------------------------------------------------------------
-- -----------------------------------------------------------------------------
-- funk.first(array, n)
-- lodash: _.first / _.take ramda: R.head / R.take
-- JS equivalent: arr[0] or arr.slice(0, n)
--
-- Without n: returns the first element (JS arr[0] — but Lua is 1-indexed).
-- With n: returns the first n elements as a new array.
-- -----------------------------------------------------------------------------
function funk.first(array, n)
if n == nil then
return array[1]
end
local result = {}
local limit = math.min(n, table.getn(array))
for i = 1, limit do
result[i] = array[i]
end
return result
end
funk.head = funk.first
funk.take = funk.first
-- -----------------------------------------------------------------------------
-- funk.last(array, n)
-- lodash: _.last / _.takeRight
-- JS equivalent: arr[arr.length - 1] or arr.slice(-n)
-- -----------------------------------------------------------------------------
function funk.last(array, n)
if n == nil then
return array[table.getn(array)]
end
local result = {}
local start = math.max(1, table.getn(array) - n + 1)
for i = start, table.getn(array) do
result[table.getn(result) + 1] = array[i]
end
return result
end
-- -----------------------------------------------------------------------------
-- funk.rest(array, index)
-- lodash: _.tail / _.drop ramda: R.tail / R.drop
-- JS equivalent: arr.slice(1) or arr.slice(index - 1)
--
-- Default index = 2 (skip the first element), matching underscore.lua.
-- index is 1-based; rest({1,2,3,4}, 3) returns {3, 4} (starts at position 3).
-- -----------------------------------------------------------------------------
function funk.rest(array, index)
index = index or 2
local result = {}
for i = index, table.getn(array) do
result[table.getn(result) + 1] = array[i]
end
return result
end
funk.tail = funk.rest
funk.drop = funk.rest
-- -----------------------------------------------------------------------------
-- funk.initial(array, n)
-- lodash: _.initial / _.dropRight
-- JS equivalent: arr.slice(0, -1) or arr.slice(0, -n)
--
-- Returns all elements except the last n (default 1).
-- -----------------------------------------------------------------------------
function funk.initial(array, n)
n = n or 1
local result = {}
for i = 1, table.getn(array) - n do
result[i] = array[i]
end
return result
end
-- -----------------------------------------------------------------------------
-- funk.slice(array, startIndex, length)
-- lodash: _.slice (but with start+length rather than start+end)
-- JS: arr.slice(start, end) uses start+end; here we use start+LENGTH.
--
-- startIndex is 1-based. Returns `length` elements beginning at startIndex.
-- -----------------------------------------------------------------------------
function funk.slice(array, startIndex, length)
local result = {}
startIndex = math.max(startIndex, 1)
local endIndex = math.min(startIndex + length - 1, table.getn(array))
for i = startIndex, endIndex do
result[table.getn(result) + 1] = array[i]
end
return result
end
-- -----------------------------------------------------------------------------
-- funk.chunk(array, size)
-- lodash: _.chunk
-- JS equivalent: custom chunking
--
-- Splits array into groups of `size`. The last group may be smaller.
-- -----------------------------------------------------------------------------
function funk.chunk(array, size)
local result = {}
local i = 1
while i <= table.getn(array) do
local chunk = {}
for j = i, math.min(i + size - 1, table.getn(array)) do
chunk[table.getn(chunk) + 1] = array[j]
end
result[table.getn(result) + 1] = chunk
i = i + size
end
return result
end
-- -----------------------------------------------------------------------------
-- funk.flatten(array)
-- lodash: _.flattenDeep ramda: R.flatten
-- JS equivalent: arr.flat(Infinity)
--
-- Recursively flattens all nested arrays into a single flat array.
-- For one-level-only flattening, see funk.flattenShallow.
-- -----------------------------------------------------------------------------
function funk.flatten(array)
local result = {}
for v in _iter(array) do
if type(v) == "table" then
local flat = funk.flatten(v)
for _, fv in ipairs(flat) do
result[table.getn(result) + 1] = fv
end
else
result[table.getn(result) + 1] = v
end
end
return result
end
-- -----------------------------------------------------------------------------
-- funk.flattenShallow(array)
-- lodash: _.flatten (one level)
-- JS equivalent: arr.flat() or arr.flat(1)
-- -----------------------------------------------------------------------------
function funk.flattenShallow(array)
local result = {}
for v in _iter(array) do
if type(v) == "table" then
for _, fv in ipairs(v) do
result[table.getn(result) + 1] = fv
end
else
result[table.getn(result) + 1] = v
end
end
return result
end
-- -----------------------------------------------------------------------------
-- funk.compact(array)
-- lodash: _.compact ramda: R.filter(Boolean)
-- JS equivalent: arr.filter(Boolean)
--
-- Removes all falsy values. In Lua only `false` and `nil` are falsy.
-- WARNING: Unlike JS, 0 and "" are NOT removed — they are truthy in Lua!
-- -----------------------------------------------------------------------------
function funk.compact(array)
return funk.filter(array, function(v) return v ~= nil and v ~= false end)
end
-- -----------------------------------------------------------------------------
-- funk.uniq(array, iteratee)
-- lodash: _.uniq / _.uniqBy ramda: R.uniq / R.uniqBy
-- JS equivalent: [...new Set(arr)] or _.uniqBy(arr, fn)
--
-- Returns a new array with duplicate values removed (keeps first occurrence).
-- Optional iteratee transforms the value used for comparison.
-- -----------------------------------------------------------------------------
function funk.uniq(array, iteratee)
local fn = iteratee or _identity
local seen = {}
local result = {}
for v in _iter(array) do
local key = fn(v)
if not seen[key] then
seen[key] = true
result[table.getn(result) + 1] = v
end
end
return result
end
funk.unique = funk.uniq
funk.uniqBy = funk.uniq
-- -----------------------------------------------------------------------------
-- funk.without(array, ...)
-- lodash: _.without
-- JS equivalent: arr.filter(v => !valuesToRemove.includes(v))
--
-- Returns a new array excluding all provided values.
-- -----------------------------------------------------------------------------
function funk.without(array, ...)
local excluded = {}
for _, v in ipairs(arg) do excluded[v] = true end
return funk.filter(array, function(v) return not excluded[v] end)
end
-- -----------------------------------------------------------------------------
-- funk.union(...)
-- lodash: _.union
-- JS equivalent: [...new Set([...arr1, ...arr2, ...])]
--
-- Returns the unique union of all provided arrays.
-- -----------------------------------------------------------------------------
function funk.union(...)
local all = {}
for _, arr in ipairs(arg) do
for _, v in ipairs(arr) do
all[table.getn(all) + 1] = v
end
end
return funk.uniq(all)
end
-- -----------------------------------------------------------------------------
-- funk.intersection(...)
-- lodash: _.intersection
-- JS equivalent: arr1.filter(v => arr2.includes(v) && arr3.includes(v) ...)
--
-- Returns elements present in ALL provided arrays.
-- -----------------------------------------------------------------------------
function funk.intersection(...)
local arrays = arg
if table.getn(arrays) == 0 then return {} end
local base = arrays[1]
local result = {}
for _, v in ipairs(base) do
local inAll = true
for i = 2, table.getn(arrays) do
if not funk.includes(arrays[i], v) then
inAll = false
break
end
end
if inAll then result[table.getn(result) + 1] = v end
end
return funk.uniq(result)
end
-- -----------------------------------------------------------------------------
-- funk.difference(array, ...)
-- lodash: _.difference
-- JS equivalent: arr.filter(v => !others.includes(v))
--
-- Returns elements from `array` NOT present in any of the other arrays.
-- -----------------------------------------------------------------------------
function funk.difference(array, ...)
local others = {}
for _, arr in ipairs(arg) do
for _, v in ipairs(arr) do others[v] = true end
end
return funk.filter(array, function(v) return not others[v] end)
end
-- -----------------------------------------------------------------------------
-- funk.zip(...)
-- lodash: _.zip ramda: R.zip / R.zipWith
-- JS equivalent: arrays[0].map((v, i) => arrays.map(a => a[i]))
--
-- Zips multiple arrays together into an array of arrays.
-- funk.zip({1,2,3}, {"a","b","c"}) → {{1,"a"}, {2,"b"}, {3,"c"}}
-- -----------------------------------------------------------------------------
function funk.zip(...)
local arrays = arg
local result = {}
local len = 0
for _, a in ipairs(arrays) do
if table.getn(a) > len then len = table.getn(a) end
end
for i = 1, len do
local row = {}
for _, a in ipairs(arrays) do
row[table.getn(row) + 1] = a[i]
end
result[i] = row
end
return result
end
-- -----------------------------------------------------------------------------
-- funk.zipObject(keys, values)
-- lodash: _.zipObject
-- JS equivalent: Object.fromEntries(keys.map((k, i) => [k, values[i]]))
--
-- Creates a table from parallel arrays of keys and values.
-- -----------------------------------------------------------------------------
function funk.zipObject(keys, values)
local result = {}
for i, k in ipairs(keys) do
result[k] = values[i]
end
return result
end
-- -----------------------------------------------------------------------------
-- funk.indexOf(array, value, fromIndex)
-- lodash: _.indexOf
-- JS equivalent: arr.indexOf(value, fromIndex)
--
-- Returns the 1-based index of the first occurrence, or -1 if not found.
-- JS uses 0-based indexing; Lua uses 1-based — this returns Lua indices.
-- -----------------------------------------------------------------------------
function funk.indexOf(array, value, fromIndex)
fromIndex = fromIndex or 1
for i = fromIndex, table.getn(array) do
if array[i] == value then return i end
end
return -1
end
-- -----------------------------------------------------------------------------
-- funk.lastIndexOf(array, value)
-- lodash: _.lastIndexOf
-- JS equivalent: arr.lastIndexOf(value)
-- -----------------------------------------------------------------------------
function funk.lastIndexOf(array, value)
for i = table.getn(array), 1, -1 do
if array[i] == value then return i end
end
return -1
end
-- -----------------------------------------------------------------------------
-- funk.range(start, stop, step)
-- lodash: _.range ramda: R.range
-- JS equivalent: Array.from({length: n}, (_, i) => start + i * step)
--
-- Creates an array of numbers from start up to (but not including) stop.
-- With one argument: range(n) → {1, 2, ..., n} (Lua 1-based convention)
-- With two arguments: range(start, stop) → {start, ..., stop-1}
-- With three arguments: range(start, stop, step)
-- Note: ramda's R.range excludes stop (like Python). This follows that.
-- -----------------------------------------------------------------------------
function funk.range(start, stop, step)
if stop == nil then
-- One-argument form: range(n) → 1..n (matches Lua 1-based indexing)
stop = start
start = 1
step = 1
else
step = step or 1
end
local result = {}
if step > 0 then
local i = start
while i < stop do
result[table.getn(result) + 1] = i
i = i + step
end
elseif step < 0 then
local i = start
while i > stop do
result[table.getn(result) + 1] = i
i = i + step
end
end
return result
end
-- -----------------------------------------------------------------------------
-- funk.reverse(array)
-- lodash: _.reverse (but non-mutating) ramda: R.reverse
-- JS equivalent: [...arr].reverse()
--
-- Returns a new reversed array. Unlike JS's Array.prototype.reverse,
-- this does NOT mutate the original.
-- -----------------------------------------------------------------------------
function funk.reverse(array)
local result = {}
for i = table.getn(array), 1, -1 do
result[table.getn(result) + 1] = array[i]
end
return result
end
-- -----------------------------------------------------------------------------
-- funk.push(array, value) / funk.pop(array)
-- JS equivalent: arr.push(v) / arr.pop()
--
-- push: appends to end, returns the array.
-- pop: removes and returns the last element.
-- -----------------------------------------------------------------------------
function funk.push(array, value)
table.insert(array, value)
return array
end
function funk.pop(array)
return table.remove(array)
end
-- -----------------------------------------------------------------------------
-- funk.unshift(array, value) / funk.shift(array)
-- JS equivalent: arr.unshift(v) / arr.shift()
--
-- unshift: prepends to front, returns the array.
-- shift: removes and returns the first element.
-- WARNING: These mutate the array (like JS Array methods).
-- -----------------------------------------------------------------------------
function funk.unshift(array, value)
table.insert(array, 1, value)
return array
end
function funk.shift(array)
return table.remove(array, 1)
end
-- -----------------------------------------------------------------------------
-- funk.splice(array, index, deleteCount, ...)
-- JS equivalent: arr.splice(index, deleteCount, ...insertItems)
--
-- Removes `deleteCount` items at `index` (1-based) and inserts items.
-- Returns the array of removed elements.
-- WARNING: Mutates the array (matches JS behavior).
-- -----------------------------------------------------------------------------
function funk.splice(array, index, deleteCount, ...)
local removed = {}
for _ = 1, deleteCount or 0 do
local v = table.remove(array, index)
if v == nil then break end
removed[table.getn(removed) + 1] = v
end
local insertItems = arg
for i = table.getn(insertItems), 1, -1 do
table.insert(array, index, insertItems[i])
end
return removed
end
-- -----------------------------------------------------------------------------
-- funk.join(array, separator)
-- lodash: _.join JS: arr.join(sep)
-- Concatenates all elements with `separator` (default ",").
-- Elements are converted to strings via tostring().
-- -----------------------------------------------------------------------------
function funk.join(array, separator)
separator = separator or ","
local strs = {}
for i, v in ipairs(array) do
strs[i] = tostring(v)
end
return table.concat(strs, separator)
end
-- -----------------------------------------------------------------------------
-- funk.concat(...)
-- lodash: _.concat JS: arr.concat(other1, other2, ...)
--
-- Merges multiple arrays into a new flat array (one level only).
-- -----------------------------------------------------------------------------
function funk.concat(...)
local result = {}
for _, arr in ipairs(arg) do
if type(arr) == "table" then
for _, v in ipairs(arr) do result[table.getn(result) + 1] = v end
else
result[table.getn(result) + 1] = arr
end
end
return result
end
-- -----------------------------------------------------------------------------
-- funk.toArray(listOrIter)
-- lodash: _.toArray
-- Materialises an iterator or returns a copy of an array.
-- -----------------------------------------------------------------------------
function funk.toArray(listOrIter)
if type(listOrIter) == "table" then
local copy = {}
for _, v in ipairs(listOrIter) do copy[table.getn(copy) + 1] = v end
return copy
end
return _toarray(listOrIter)
end
-- ---------------------------------------------------------------------------
-- ═══════════════════════════════════════════════════════════════════════════
-- SECTION 3 — OBJECT / TABLE FUNCTIONS
-- Operate on key-value tables (like JS plain objects / Maps).
-- ═══════════════════════════════════════════════════════════════════════════
-- ---------------------------------------------------------------------------
-- -----------------------------------------------------------------------------
-- funk.keys(obj) / funk.values(obj)
-- lodash: _.keys / _.values ramda: R.keys / R.values
-- JS equivalent: Object.keys(obj) / Object.values(obj)
--
-- Note: In Lua `pairs` iterates ALL table keys (including non-integer ones).
-- Order is NOT guaranteed (same caveat applies in JS for non-integer keys).
-- -----------------------------------------------------------------------------
function funk.keys(obj)
local result = {}