-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmoses.lua
More file actions
1797 lines (1642 loc) · 56.2 KB
/
moses.lua
File metadata and controls
1797 lines (1642 loc) · 56.2 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
--- *Utility-belt library for functional programming in Lua.*<br/>
-- Source on [Github](http://github.com/Yonaba/Moses)
-- @author [Roland Yonaba](http://github.com/Yonaba)
-- @copyright 2012-2014
-- @license [MIT](http://www.opensource.org/licenses/mit-license.php)
-- @release 1.4.0
-- @module moses
local _MODULEVERSION = '1.4.0'
-- Internalisation
local next, type, unpack, select, pcall = next, type, unpack, select, pcall
local setmetatable, getmetatable = setmetatable, getmetatable
local t_insert, t_sort = table.insert, table.sort
local t_remove,t_concat = table.remove, table.concat
local randomseed, random, huge = math.randomseed, math.random, math.huge
local floor, max, min = math.floor, math.max, math.min
local rawget = rawget
local unpack = unpack
local pairs,ipairs = pairs,ipairs
local _ = {}
-- ======== Private helpers
local function f_max(a,b) return a>b end
local function f_min(a,b) return a<b end
local function clamp(var,a,b) return (var<a) and a or (var>b and b or var) end
local function isTrue(_,value) return value and true end
local function iNot(value) return not value end
local function count(t) -- raw count of items in an map-table
local i = 0
for k,v in pairs(t) do i = i + 1 end
return i
end
local function extract(list,comp,transform,...) -- extracts value from a list
local _ans
local transform = transform or _.identity
for index,value in pairs(list) do
if not _ans then _ans = transform(value,...)
else
local value = transform(value,...)
_ans = comp(_ans,value) and _ans or value
end
end
return _ans
end
local function partgen(t, n, f) -- generates array partitions
for i = 0, #t, n do
local s = _.slice(t, i+1, i+n)
if #s>0 then f(s) end
end
end
local function permgen(t, n, f) -- taken from PiL: http://www.lua.org/pil/9.3.html
if n == 0 then f(t) end
for i = 1,n do
t[n], t[i] = t[i], t[n]
permgen(t, n-1, f)
t[n], t[i] = t[i], t[n]
end
end
-- Internal counter for unique ids generation
local unique_id_counter = -1
--- Table functions
-- @section Table functions
--- Iterates on each key-value pairs in a table. Calls function `f(key, value)` at each step of iteration.
-- <br/><em>Aliased as `forEach`</em>.
-- @name each
-- @tparam table t a table
-- @tparam function f an iterator function, prototyped as `f(key, value, ...)`
-- @tparam[opt] vararg ... Optional extra-args to be passed to function `f`
-- @see eachi
function _.each(t, f, ...)
for index,value in pairs(t) do
f(index,value,...)
end
end
--- Iterates on each integer key-value pairs in a table. Calls function `f(key, value)`
-- only on values at integer key in a given collection. The table can be a sparse array,
-- or map-like. Iteration will start from the lowest integer key found to the highest one.
-- <br/><em>Aliased as `forEachi`</em>.
-- @name eachi
-- @tparam table t a table
-- @tparam function f an iterator function, prototyped as `f(key, value, ...)`
-- @tparam[opt] vararg ... Optional extra-args to be passed to function `f`
-- @see each
function _.eachi(t, f, ...)
local lkeys = _.sort(_.select(_.keys(t), function(k,v)
return _.isInteger(v)
end))
for k, key in ipairs(lkeys) do
f(key, t[key],...)
end
end
--- Returns an array of values at specific indexes and keys.
-- @name at
-- @tparam table t a table
-- @tparam vararg ... A variable number of indexes or keys to extract values
-- @treturn table an array-list of values from the passed-in table
function _.at(t, ...)
local values = {}
for i, key in ipairs({...}) do
if _.has(t, key) then values[#values+1] = t[key] end
end
return values
end
--- Counts occurrences of a given value in a table. Uses @{isEqual} to compare values.
-- @name count
-- @tparam table t a table
-- @tparam[opt] value value a value to be searched in the table. If not given, the @{size} of the table will be returned
-- @treturn number the count of occurrences of `value`
-- @see countf
-- @see size
function _.count(t, value)
if _.isNil(value) then return _.size(t) end
local count = 0
_.each(t, function(k,v)
if _.isEqual(v, value) then count = count + 1 end
end)
return count
end
--- Counts occurrences validating a predicate. Same as @{count}, but uses an iterator.
-- Returns the count for values passing the test `f(key, value, ...)`
-- @name countf
-- @tparam table t a table
-- @tparam function f an iterator function, prototyped as `f(key, value, ...)`
-- @tparam[opt] vararg ... Optional extra-args to be passed to function `f`
-- @treturn number the count of values validating the predicate
-- @see count
-- @see size
function _.countf(t, f, ...)
return _.count(_.map(t, f, ...), true)
end
--- Iterates through a table and loops `n` times. The full iteration loop will be
-- repeated `n` times (or forever, if `n` is omitted). In case `n` is lower or equal to 0, it returns
-- an empty function.
-- <br/><em>Aliased as `loop`</em>.
-- @name cycle
-- @tparam table t a table
-- @tparam number n the number of loops
-- @treturn function an iterator function yielding key-value pairs from the passed-in table.
function _.cycle(t, n)
n = n or 1
if n<=0 then return function() end end
local k, fk
local i = 0
while true do
return function()
k = k and next(t,k) or next(t)
fk = not fk and k or fk
if n then
i = (k==fk) and i+1 or i
if i > n then
return
end
end
return k, t[k]
end
end
end
--- Maps function `f(key, value)` on all key-value pairs. Collects
-- and returns the results as a table.
-- <br/><em>Aliased as `collect`</em>.
-- @name map
-- @tparam table t a table
-- @tparam function f an iterator function, prototyped as `f(key, value, ...)`
-- @tparam[opt] vararg ... Optional extra-args to be passed to function `f`
-- @treturn table a table of results
function _.map(t, f, ...)
local _t = {}
for index,value in pairs(t) do
_t[index] = f(index,value,...)
end
return _t
end
--- Reduces a table, left-to-right. Folds the table from the first element to the last element
-- to into a single value, with respect to a given iterator and an initial state.
-- The given function takes a state and a value and returns a new state.
-- <br/><em>Aliased as `inject`, `foldl`</em>.
-- @name reduce
-- @tparam table t a table
-- @tparam function f an iterator function, prototyped as `f(state, value)`
-- @tparam[opt] state state an initial state of reduction. Defaults to the first value in the table.
-- @treturn state state the final state of reduction
-- @see reduceRight
function _.reduce(t, f, state)
for __,value in pairs(t) do
if state == nil then state = value
else state = f(state,value)
end
end
return state
end
--- Reduces a table, right-to-left. Folds the table from the last element to the first element
-- to single value, with respect to a given iterator and an initial state.
-- The given function takes a state and a value, and returns a new state.
-- <br/><em>Aliased as `injectr`, `foldr`</em>.
-- @name reduceRight
-- @tparam table t a table
-- @tparam function f an iterator function, prototyped as `f(state,value)`
-- @tparam[opt] state state an initial state of reduction. Defaults to the last value in the table.
-- @treturn state state the final state of reduction
-- @see reduce
function _.reduceRight(t, f, state)
return _.reduce(_.reverse(t),f,state)
end
--- Reduces a table while saving intermediate states. Folds the table left-to-right
-- to a single value, with respect to a given iterator and an initial state. The given function
-- takes a state and a value, and returns a new state. It returns an array of intermediate states.
-- <br/><em>Aliased as `mapr`</em>
-- @name mapReduce
-- @tparam table t a table
-- @tparam function f an iterator function, prototyped as `f(state, value)`
-- @tparam[opt] state state an initial state of reduction. Defaults to the first value in the table.
-- @treturn table an array of states
-- @see mapReduceRight
function _.mapReduce(t, f, state)
local _t = {}
for i,value in pairs(t) do
_t[i] = not state and value or f(state,value)
state = _t[i]
end
return _t
end
--- Reduces a table while saving intermediate states. Folds the table right-to-left
-- to a single value, with respect to a given iterator and an initial state. The given function
-- takes a state and a value, and returns a new state. It returns an array of intermediate states.
-- <br/><em>Aliased as `maprr`</em>
-- @name mapReduceRight
-- @tparam table t a table
-- @tparam function f an iterator function, prototyped as `f(state,value)`
-- @tparam[opt] state state an initial state of reduction. Defaults to the last value in the table.
-- @treturn table an array of states
-- @see mapReduce
function _.mapReduceRight(t, f, state)
return _.mapReduce(_.reverse(t),f,state)
end
--- Search for a value in a table. It does not search in nested tables.
-- <br/><em>Aliased as `any`, `some`</em>
-- @name include
-- @tparam table t a table
-- @tparam value|function value a value to search for
-- @treturn boolean a boolean : `true` when found, `false` otherwise
-- @see detect
-- @see contains
function _.include(t,value)
local _iter = _.isFunction(value) and value or _.isEqual
for __,v in pairs(t) do
if _iter(v,value) then return true end
end
return false
end
--- Search for a value in a table. Returns the key of the value if found.
-- It does not search in nested tables.
-- @name detect
-- @tparam table t a table
-- @tparam value value a value to search for
-- @treturn key the value key or __nil__
-- @see include
-- @see contains
function _.detect(t, value)
local _iter = _.isFunction(value) and value or _.isEqual
for key,arg in pairs(t) do
if _iter(arg,value) then return key end
end
end
--- Checks if a value is present in a table.
-- @name contains
-- @tparam table t a table
-- @tparam value value a value to search for
-- @treturn boolean true if present, otherwise false
-- @see include
-- @see detect
function _.contains(t, value)
return _.toBoolean(_.detect(t, value))
end
--- Returns the first value having specified keys `props`.
-- @function findWhere
-- @tparam table t a table
-- @tparam table props a set of keys
-- @treturn value a value from the passed-in table
function _.findWhere(t, props)
local index = _.detect(t, function(v)
for key in pairs(props) do
if props[key] ~= v[key] then return false end
end
return true
end)
return index and t[index]
end
--- Selects and extracts values passing an iterator test.
-- <br/><em>Aliased as `filter`</em>.
-- @name select
-- @tparam table t a table
-- @tparam function f an iterator function, prototyped as `f(key, value, ...)`
-- @tparam[opt] vararg ... Optional extra-args to be passed to function `f`
-- @treturn table the selected values
-- @see reject
function _.select(t, f, ...)
local _mapped = _.map(t, f, ...)
local _t = {}
for index,value in pairs(_mapped) do
if value then _t[#_t+1] = t[index] end
end
return _t
end
--- Clones a table while dropping values passing an iterator test.
-- <br/><em>Aliased as `discard`</em>
-- @name reject
-- @tparam table t a table
-- @tparam function f an iterator function, prototyped as `f(key, value, ...)`
-- @tparam[opt] vararg ... Optional extra-args to be passed to function `f`
-- @treturn table the remaining values
-- @see select
function _.reject(t, f, ...)
local _mapped = _.map(t,f,...)
local _t = {}
for index,value in pairs (_mapped) do
if not value then _t[#_t+1] = t[index] end
end
return _t
end
--- Checks if all values in a table are passing an iterator test.
-- <br/><em>Aliased as `every`</em>
-- @name all
-- @tparam table t a table
-- @tparam function f an iterator function, prototyped as `f(key, value, ...)`
-- @tparam[opt] vararg ... Optional extra-args to be passed to function `f`
-- @treturn boolean `true` if all values passes the predicate, `false` otherwise
function _.all(t, f, ...)
return ((#_.select(_.map(t,f,...), isTrue)) == (#t))
end
--- Invokes a method on each value in a table.
-- @name invoke
-- @tparam table t a table
-- @tparam function method a function, prototyped as `f(value, ...)`
-- @tparam[opt] vararg ... Optional extra-args to be passed to function `method`
-- @treturn result the result(s) of method call `f(value, ...)`
-- @see pluck
function _.invoke(t, method, ...)
local args = {...}
return _.map(t, function(__,v)
if _.isTable(v) then
if _.has(v,method) then
if _.isCallable(v[method]) then
return v[method](v,unpack(args))
else
return v[method]
end
else
if _.isCallable(method) then
return method(v,unpack(args))
end
end
elseif _.isCallable(method) then
return method(v,unpack(args))
end
end)
end
--- Extracts property-values from a table of values.
-- @name pluck
-- @tparam table t a table
-- @tparam string a property, will be used to index in each value: `value[property]`
-- @treturn table an array of values for the specified property
function _.pluck(t, property)
return _.reject(_.map(t,function(__,value)
return value[property]
end), iNot)
end
--- Returns the max value in a collection. If an transformation function is passed, it will
-- be used to extract the value by which all objects will be sorted.
-- @name max
-- @tparam table t a table
-- @tparam[opt] function transform an transformation function, prototyped as `transform(value,...)`, defaults to @{identity}
-- @tparam[optchain] vararg ... Optional extra-args to be passed to function `transform`
-- @treturn value the maximum value found
-- @see min
function _.max(t, transform, ...)
return extract(t, f_max, transform, ...)
end
--- Returns the min value in a collection. If an transformation function is passed, it will
-- be used to extract the value by which all objects will be sorted.
-- @name min
-- @tparam table t a table
-- @tparam[opt] function transform an transformation function, prototyped as `transform(value,...)`, defaults to @{identity}
-- @tparam[optchain] vararg ... Optional extra-args to be passed to function `transform`
-- @treturn value the minimum value found
-- @see max
function _.min(t, transform, ...)
return extract(t, f_min, transform, ...)
end
--- Returns a shuffled copy of a given collection. If a seed is provided, it will
-- be used to init the random number generator (via `math.randomseed`).
-- @name shuffle
-- @tparam table t a table
-- @tparam[opt] number seed a seed
-- @treturn table a shuffled copy of the given table
function _.shuffle(t, seed)
if seed then randomseed(seed) end
local _shuffled = {}
_.each(t,function(index,value)
local randPos = floor(random()*index)+1
_shuffled[index] = _shuffled[randPos]
_shuffled[randPos] = value
end)
return _shuffled
end
--- Checks if two tables are the same. It compares if both tables features the same values,
-- but not necessarily at the same keys.
-- @name same
-- @tparam table a a table
-- @tparam table b another table
-- @treturn boolean `true` or `false`
function _.same(a, b)
return _.all(a, function (i,v) return _.include(b,v) end)
and _.all(b, function (i,v) return _.include(a,v) end)
end
--- Sorts a table, in-place. If a comparison function is given, it will be used to sort values.
-- @name sort
-- @tparam table t a table
-- @tparam[opt] function comp a comparison function prototyped as `comp(a,b)`, defaults to <tt><</tt> operator.
-- @treturn table the given table, sorted.
function _.sort(t, comp)
t_sort(t, comp)
return t
end
--- Splits a table into subsets. Each subset feature values from the original table grouped
-- by the result of passing it through an iterator.
-- @name groupBy
-- @tparam table t a table
-- @tparam function iter an iterator function, prototyped as `iter(key, value, ...)`
-- @tparam[opt] vararg ... Optional extra-args to be passed to function `iter`
-- @treturn table a new table with values grouped by subsets
function _.groupBy(t, iter, ...)
local vararg = {...}
local _t = {}
_.each(t, function(i,v)
local _key = iter(i,v, unpack(vararg))
if _t[_key] then _t[_key][#_t[_key]+1] = v
else _t[_key] = {v}
end
end)
return _t
end
--- Groups values in a collection and counts them.
-- @name countBy
-- @tparam table t a table
-- @tparam function iter an iterator function, prototyped as `iter(key, value, ...)`
-- @tparam[opt] vararg ... Optional extra-args to be passed to function `iter`
-- @treturn table a new table with subsets names paired with their count
function _.countBy(t, iter, ...)
local vararg = {...}
local stats = {}
_.each(t,function(i,v)
local key = iter(i,v,unpack(vararg))
stats[key] = (stats[key] or 0) +1
end)
return stats
end
--- Counts the number of values in a collection. If being passed more than one args
-- it will return the count of all passed-in args.
-- @name size
-- @tparam[opt] vararg ... Optional variable number of arguments
-- @treturn number a count
-- @see count
-- @see countf
function _.size(...)
local args = {...}
local arg1 = args[1]
if _.isNil(arg1) then
return 0
elseif _.isTable(arg1) then
return count(args[1])
else
return count(args)
end
end
--- Checks if all the keys of `other` table exists in table `t`. It does not
-- compares values. The test is not commutative, i.e table `t` may contains keys
-- not existing in `other`.
-- @name containsKeys
-- @tparam table t a table
-- @tparam table other another table
-- @treturn boolean `true` or `false`
-- @see sameKeys
function _.containsKeys(t, other)
for key in pairs(other) do
if not t[key] then return false end
end
return true
end
--- Checks if both given tables have the same keys. It does not compares values.
-- @name sameKeys
-- @tparam table tA a table
-- @tparam table tB another table
-- @treturn boolean `true` or `false`
-- @see containsKeys
function _.sameKeys(tA, tB)
for key in pairs(tA) do
if not tB[key] then return false end
end
for key in pairs(tB) do
if not tA[key] then return false end
end
return true
end
--- Array functions
-- @section Array functions
--- Converts a vararg list to an array-list.
-- @name toArray
-- @tparam[opt] vararg ... Optional variable number of arguments
-- @treturn table an array-list of all passed-in args
function _.toArray(...) return {...} end
--- Looks for the first occurrence of a given value in an array. Returns the value index if found.
-- @name find
-- @tparam table array an array of values
-- @tparam value value a value to search for
-- @tparam[opt] number from the index from where to start the search. Defaults to 1.
-- @treturn number|nil the index of the value if found in the array, `nil` otherwise.
function _.find(array, value, from)
for i = from or 1, #array do
if _.isEqual(array[i], value) then return i end
end
end
--- Reverses values in a given array. The passed-in array should not be sparse.
-- @name reverse
-- @tparam table array an array
-- @treturn table a copy of the given array, reversed
function _.reverse(array)
local _array = {}
for i = #array,1,-1 do
_array[#_array+1] = array[i]
end
return _array
end
--- Collects values from a given array. The passed-in array should not be sparse.
-- This function collects values as long as they satisfy a given predicate.
-- Therefore, it returns on the first falsy test.
-- <br/><em>Aliased as `takeWhile`</em>
-- @name selectWhile
-- @tparam table array an array
-- @tparam function f an iterator function prototyped as `f(key, value, ...)`
-- @tparam[opt] vararg ... Optional extra-args to be passed to function `f`
-- @treturn table a new table containing all values collected
-- @see dropWhile
function _.selectWhile(array, f, ...)
local t = {}
for i,v in ipairs(array) do
if f(i,v,...) then t[i] = v else break end
end
return t
end
--- Collects values from a given array. The passed-in array should not be sparse.
-- This function collects values as long as they do not satisfy a given predicate.
-- Therefore it returns on the first true test.
-- <br/><em>Aliased as `rejectWhile`</em>
-- @name dropWhile
-- @tparam table array an array
-- @tparam function f an iterator function prototyped as `f(key,value,...)`
-- @tparam[opt] vararg ... Optional extra-args to be passed to function `f`
-- @treturn table a new table containing all values collected
-- @selectWhile
function _.dropWhile(array, f, ...)
local _i
for i,v in ipairs(array) do
if not f(i,v,...) then
_i = i
break
end
end
if _.isNil(_i) then return {} end
return _.rest(array,_i)
end
--- Returns the index at which a value should be inserted. This returned index is determined so
-- that it maintains the sort. If a comparison function is passed, it will be used to sort all
-- values.
-- @name sortedIndex
-- @tparam table array an array
-- @tparam value the value to be inserted
-- @tparam[opt] function comp an comparison function prototyped as `f(a, b)`, defaults to <tt><</tt> operator.
-- @tparam[optchain] boolean sort whether or not the passed-in array should be sorted
-- @treturn number the index at which the passed-in value should be inserted
function _.sortedIndex(array, value, comp, sort)
local _comp = comp or f_min
if sort then _.sort(array,_comp) end
for i = 1,#array do
if not _comp(array[i],value) then return i end
end
return #array+1
end
--- Returns the index of a given value in an array. If the passed-in value exists
-- more than once in the array, it will return the index of the first occurrence.
-- @name indexOf
-- @tparam table array an array
-- @tparam value the value to search for
-- @treturn number|nil the index of the passed-in value
-- @see lastIndexOf
function _.indexOf(array, value)
for k = 1,#array do
if array[k] == value then return k end
end
end
--- Returns the index of the last occurrence of a given value.
-- @name lastIndexOf
-- @tparam table array an array
-- @tparam value the value to search for
-- @treturn number|nil the index of the last occurrence of the passed-in value or __nil__
-- @see indexOf
function _.lastIndexOf(array, value)
local key = _.indexOf(_.reverse(array),value)
if key then return #array-key+1 end
end
--- Adds all passed-in values at the top of an array. The last arguments will bubble to the
-- top of the given array.
-- @name addTop
-- @tparam table array an array
-- @tparam vararg ... a variable number of arguments
-- @treturn table the passed-in array
-- @see push
function _.addTop(array, ...)
_.each({...},function(i,v) t_insert(array,1,v) end)
return array
end
--- Pushes all passed-in values at the end of an array.
-- @name push
-- @tparam table array an array
-- @tparam vararg ... a variable number of arguments
-- @treturn table the passed-in array
-- @see addTop
function _.push(array, ...)
_.each({...}, function(i,v) array[#array+1] = v end)
return array
end
--- Removes and returns the values at the top of a given array.
-- <br/><em>Aliased as `shift`</em>
-- @name pop
-- @tparam table array an array
-- @tparam[opt] number n the number of values to be popped. Defaults to 1.
-- @treturn vararg a vararg list of values popped from the array
-- @see unshift
function _.pop(array, n)
n = min(n or 1, #array)
local ret = {}
for i = 1, n do
local retValue = array[1]
ret[#ret + 1] = retValue
t_remove(array,1)
end
return unpack(ret)
end
--- Removes and returns the values at the end of a given array.
-- @name unshift
-- @tparam table array an array
-- @tparam[opt] number n the number of values to be unshifted. Defaults to 1.
-- @treturn vararg a vararg list of values
-- @see pop
function _.unshift(array, n)
n = min(n or 1, #array)
local ret = {}
for i = 1, n do
local retValue = array[#array]
ret[#ret + 1] = retValue
t_remove(array)
end
return unpack(ret)
end
--- Removes all provided values in a given array.
-- <br/><em>Aliased as `remove`</em>
-- @name pull
-- @tparam table array an array
-- @tparam vararg ... a variable number of values to be removed from the array
-- @treturn table the passed-in array
function _.pull(array, ...)
for __, rmValue in ipairs({...}) do
for i = #array, 1, -1 do
if _.isEqual(array[i], rmValue) then
t_remove(array, i)
end
end
end
return array
end
--- Trims all values indexed within the range `[start, finish]`.
-- <br/><em>Aliased as `rmRange`</em>
-- @name removeRange
-- @tparam table array an array
-- @tparam[opt] number start the lower bound index, defaults to the first index in the array.
-- @tparam[optchain] number finish the upper bound index, defaults to the array length.
-- @treturn table the passed-in array
function _.removeRange(array, start, finish)
local array = _.clone(array)
local i,n = (next(array)),#array
if n < 1 then return array end
start = clamp(start or i,i,n)
finish = clamp(finish or n,i,n)
if finish < start then return array end
local count = finish - start + 1
local i = start
while count > 0 do
t_remove(array,i)
count = count - 1
end
return array
end
--- Chunks together consecutive values. Values are chunked on the basis of the return
-- value of a provided predicate `f(key, value, ...)`. Consecutive elements which return
-- the same value are chunked together. Leaves the first argument untouched if it is not an array.
-- @name chunk
-- @tparam table array an array
-- @tparam function f an iterator function prototyped as `f(key, value, ...)`
-- @tparam[opt] vararg ... Optional extra-args to be passed to function `f`
-- @treturn table a table of chunks (arrays)
-- @see zip
function _.chunk(array, f, ...)
if not _.isArray(array) then return array end
local ch, ck, prev = {}, 0
local mask = _.map(array, f,...)
_.each(mask, function(k,v)
prev = (prev==nil) and v or prev
ck = ((v~=prev) and (ck+1) or ck)
if not ch[ck] then
ch[ck] = {array[k]}
else
ch[ck][#ch[ck]+1] = array[k]
end
prev = v
end)
return ch
end
--- Slices values indexed within `[start, finish]` range.
-- <br/><em>Aliased as `_.sub`</em>
-- @name slice
-- @tparam table array an array
-- @tparam[opt] number start the lower bound index, defaults to the first index in the array.
-- @tparam[optchain] number finish the upper bound index, defaults to the array length.
-- @treturn table a new array
function _.slice(array, start, finish)
return _.select(array, function(index)
return (index >= (start or next(array)) and index <= (finish or #array))
end)
end
--- Returns the first N values in an array.
-- <br/><em>Aliased as `head`, `take`</em>
-- @name first
-- @tparam table array an array
-- @tparam[opt] number n the number of values to be collected, defaults to 1.
-- @treturn table a new array
-- @see initial
-- @see last
-- @see rest
function _.first(array, n)
local n = n or 1
return _.slice(array,1, min(n,#array))
end
--- Returns all values in an array excluding the last N values.
-- @name initial
-- @tparam table array an array
-- @tparam[opt] number n the number of values to be left, defaults to the array length.
-- @treturn table a new array
-- @see first
-- @see last
-- @see rest
function _.initial(array, n)
if n and n < 0 then return end
return _.slice(array,1, n and #array-(min(n,#array)) or #array-1)
end
--- Returns the last N values in an array.
-- @name last
-- @tparam table array an array
-- @tparam[opt] number n the number of values to be collected, defaults to the array length.
-- @treturn table a new array
-- @see first
-- @see initial
-- @see rest
function _.last(array,n)
if n and n <= 0 then return end
return _.slice(array,n and #array-min(n-1,#array-1) or 2,#array)
end
--- Trims all values before index.
-- <br/><em>Aliased as `tail`</em>
-- @name rest
-- @tparam table array an array
-- @tparam[opt] number index an index, defaults to 1
-- @treturn table a new array
-- @see first
-- @see initial
-- @see last
function _.rest(array,index)
if index and index > #array then return {} end
return _.slice(array,index and max(1,min(index,#array)) or 1,#array)
end
--- Trims all falsy (false and nil) values.
-- @name compact
-- @tparam table array an array
-- @treturn table a new array
function _.compact(array)
return _.reject(array, function (_,value)
return not value
end)
end
--- Flattens a nested array. Passing `shallow` will only flatten at the first level.
-- @name flatten
-- @tparam table array an array
-- @tparam[opt] boolean shallow specifies the flattening depth
-- @treturn table a new array, flattened
function _.flatten(array, shallow)
local shallow = shallow or false
local new_flattened
local _flat = {}
for key,value in pairs(array) do
if _.isTable(value) then
new_flattened = shallow and value or _.flatten (value)
_.each(new_flattened, function(_,item) _flat[#_flat+1] = item end)
else _flat[#_flat+1] = value
end
end
return _flat
end
--- Returns values from an array not present in all passed-in args.
-- <br/><em>Aliased as `without` and `diff`</em>
-- @name difference
-- @tparam table array an array
-- @tparam table another array
-- @treturn table a new array
-- @see union
-- @see intersection
-- @see symmetricDifference
function _.difference(array, array2)
if not array2 then return _.clone(array) end
return _.select(array,function(i,value)
return not _.include(array2,value)
end)
end
--- Returns the duplicate-free union of all passed in arrays.
-- @name union
-- @tparam vararg ... a variable number of arrays arguments
-- @treturn table a new array
-- @see difference
-- @see intersection
-- @see symmetricDifference
function _.union(...)
return _.uniq(_.flatten({...}))
end
--- Returns the intersection of all passed-in arrays.
-- Each value in the result is present in each of the passed-in arrays.
-- @name intersection
-- @tparam table array an array
-- @tparam vararg ... a variable number of array arguments
-- @treturn table a new array
-- @see difference
-- @see union
-- @see symmetricDifference
function _.intersection(array, ...)
local arg = {...}
local _intersect = {}
for i,value in ipairs(array) do
if _.all(arg,function(i,v)
return _.include(v,value)
end) then
t_insert(_intersect,value)
end
end
return _intersect
end
--- Performs a symmetric difference. Returns values from `array` not present in `array2` and also values
-- from `array2` not present in `array`.
-- <br/><em>Aliased as `symdiff`</em>
-- @name symmetricDifference
-- @tparam table array an array
-- @tparam table array2 another array
-- @treturn table a new array
-- @see difference
-- @see union
-- @see intersection
function _.symmetricDifference(array, array2)
return _.difference(
_.union(array, array2),
_.intersection(array,array2)
)
end
--- Produces a duplicate-free version of a given array.
-- <br/><em>Aliased as `uniq`</em>
-- @name unique
-- @tparam table array an array
-- @treturn table a new array, duplicate-free
-- @see isunique
function _.unique(array)
local ret = {}
for i = 1, #array do
if not _.find(ret, array[i]) then
ret[#ret+1] = array[i]
end
end
return ret
end
--- Checks if a given array contains distinct values. Such an array is made of distinct elements,
-- which only occur once in this array.
-- <br/><em>Aliased as `isuniq`</em>
-- @name isunique
-- @tparam table array an array
-- @treturn boolean `true` if the given array is unique, `false` otherwise.
-- @see unique
function _.isunique(array)
return _.isEqual(array, _.unique(array))
end
--- Merges values of each of the passed-in arrays in subsets.
-- Only values indexed with the same key in the given arrays are merged in the same subset.
-- @name zip
-- @tparam vararg ... a variable number of array arguments
-- @treturn table a new array
function _.zip(...)
local arg = {...}
local _len = _.max(_.map(arg,function(i,v)
return #v
end))
local _ans = {}
for i = 1,_len do
_ans[i] = _.pluck(arg,i)
end
return _ans
end
--- Clones `array` and appends `other` values.
-- @name append
-- @tparam table array an array
-- @tparam table other an array
-- @treturn table a new array
function _.append(array, other)
local t = {}
for i,v in ipairs(array) do t[i] = v end