forked from cromo/underscore.cpp
-
Notifications
You must be signed in to change notification settings - Fork 2
/
lodash.hpp
2003 lines (1752 loc) · 70.5 KB
/
lodash.hpp
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
#ifndef UNDERSCORE_UNDERSCORE_H_
#define UNDERSCORE_UNDERSCORE_H_
#define UNDERSCORE_BONUS
#define _VECTOR(...) <std::vector<__VA_ARGS__>>
#define _IDENTITY_LAMBDA [](const auto& _) { return _; }
#include <cstdlib>
#include <algorithm>
#include <functional>
#include <iterator>
#include <map>
#include <vector>
#include <utility>
//#include <functional.h>
//using namespace sfinktah::functional;
//// not used at present, but a really handy example of dealing with multiple argument passing and rvalue and perfect forwarding
//// (from Scott Meyers, in his "Effective Modern C++")
//template <typename Function, typename... Args>
//inline auto reallyAsync(Function&& f, Args&&... params) {
// // Maybe we could use it with std::apply - see http://en.cppreference.com/w/cpp/utility/apply
// // and http://en.cppreference.com/w/cpp/utility/functional/invoke
// return std::async(std::launch::async, std::forward<Function>(f),
// std::forward<Args>(params)...);
//}
//
namespace _
{
#ifdef min
#undef min
#endif
#ifdef max
#undef max
#endif
namespace helper
{
// For a number of Underscore functions, the elements of a container are
// transformed in some way, and the results are placed in another container.
// To be able to support different kinds of containers, a way of choosing the
// proper method for addition to the result container must be called, but these
// methods are not uniform across the standard library.
// To get around this, the correct function to call must be determined at
// compile time using metafunctions and SFINAE.
// Because the body to determine whether or not a given member function is
// relatively large, the HAS_MEMBER_FUNCTION macro is temporarily defined to
// help reduce code size.
// This is from http://stackoverflow.com/a/264088/1256
#define HAS_MEMBER_FUNCTION(func, name) \
template <typename T, typename Sign> \
struct name \
{ \
typedef char yes[1]; \
typedef char no[2]; \
template <typename U, U> \
struct type_check; \
template <typename _1> \
static yes& chk(type_check<Sign, &_1::func>*); \
template <typename> \
static no& chk(...); \
static bool const value = sizeof(chk<T>(0)) == sizeof(yes); \
}
// Use the macro to define metafunctions for the various insertion methods that
// Underscore supports. Primarily, these will be single parameter member
// functions that are used across multiple types in the standard library.
HAS_MEMBER_FUNCTION(push_back, HasPushBack);
HAS_MEMBER_FUNCTION(insert, HasInsert);
HAS_MEMBER_FUNCTION(key, HasKey);
HAS_MEMBER_FUNCTION(is_object, HasIsObject);
HAS_MEMBER_FUNCTION(to_cbor, HasToCbor); // json iterator
// Remove the macro so that it doesn't pollute the global scope.
#undef HAS_MEMBER_FUNCTION
// To simplify function declarations later, the insertion capabilities for a
// given type are simply listed in a struct.
template <typename Container>
struct ContainerMethods
{
static bool const has_push_back =
HasPushBack<
Container,
void (Container::*)
(const typename Container::value_type&)
>::value;
static bool const has_insert =
HasInsert<
Container,
std::pair<typename Container::iterator, bool>(Container::*)
(const typename Container::value_type&)
>::value;
static bool const has_is_object =
HasIsObject<
Container,
std::pair<typename Container::iterator, bool>(Container::*)
(const typename Container::value_type&)
>::value;
static bool const has_to_cbor =
HasToCbor<
Container,
void (Container::*)
(const typename Container::value_type&)
>::value;
};
//template <typename Iterator>
//struct IteratorMethods
//{
// static bool const has_key =
// HasKey<
// Iterator,
// void (Iterator::*)
// (const typename Iterator::value_type&)
// >::value;
//};
template <typename Container>
struct HasSupportedMethod
{
static bool const value = 0
|| ContainerMethods<Container>::has_push_back
|| ContainerMethods<Container>::has_insert;
};
template <typename Container>
struct HasJsonTraits
{
static bool const value = 0
|| ContainerMethods<Container>::has_is_object
|| ContainerMethods<Container>::has_to_cbor;
};
// A simple implementation of enable_if allows alternative functions to be
// selected at compile time.
// This is from http://stackoverflow.com/a/264088/1256
template <bool C, typename T = void>
struct enable_if { typedef T type; };
template <typename T>
struct enable_if<false, T> {};
// This `enable_if_t` syntactic sugar is really not worth the one-time use
template<bool B, typename T = void>
using enable_if_t = typename std::enable_if<B, T>::type;
template <typename Container>
enable_if_t<ContainerMethods<Container>::has_insert, void>
insert(Container& container, typename Container::value_type const& value)
{
container.insert(value);
}
template <typename Container>
typename enable_if<ContainerMethods<Container>::has_push_back, void>::type
push_back(Container& container, typename Container::value_type const& value)
{
container.push_back(value);
}
template <typename Container>
typename enable_if<!ContainerMethods<Container>::has_push_back, void>::type
push_back(Container& container, typename Container::value_type const& value)
{
insert(container, value);
}
template <typename Container>
typename enable_if<HasSupportedMethod<Container>::value, void>::type
add_to_container(Container& container, typename Container::value_type const& value)
{
push_back(container, value);
}
template <typename Container>
typename enable_if<HasSupportedMethod<Container>::value, void>::type
add_to_container(Container& container, typename Container::key_type const& key, typename Container::value_type const& value)
{
container.insert(container, value);
}
template <typename T>
struct is_void
{
static bool const value = false;
};
template <>
struct is_void<void>
{
static bool const value = true;
};
template<typename T>
constexpr T clamp(T value, T min, T max) {
return (
value > max ? max :
value < min ? min :
value
);
}
// https://stackoverflow.com/questions/9044866/how-to-get-the-number-of-arguments-of-stdfunction/9044927#9044927
template<typename T>
struct count_arg;
template<typename R, typename ...Args>
struct count_arg<std::function<R(Args...)>>
{
static const size_t value = sizeof...(Args);
};
//#include <type_traits>
//#include <utility>
//#include <map>
// https://stackoverflow.com/questions/43992510/enable-if-to-check-if-value-type-of-iterator-is-a-pair/43993493#43993493
template <typename>
struct is_pair : std::false_type
{ };
template <typename T, typename U>
struct is_pair<std::pair<T, U>> : std::true_type
{ };
//int main()
//{
// std::map<int, int> foo{
// { 1, 2 },
// { 3, 4 },
// };
// do_stuff(foo.begin());
// return 0;
//}
} // namespace helper
// Collections
// each/for_each
// http://en.cppreference.com/w/cpp/algorithm/for_each
template <typename Container, typename Function>
void each(Container container, Function function)
{
//function - function object, to be applied to the result of dereferencing every iterator in the range[first, last)
//The signature of the function should be equivalent to the following :
// void fun(const Type &a);
//The signature does not need to have `const &`.
//The type Type must be such that an object of type InputIt can be dereferenced and then implicitly converted to Type.
std::for_each(container.begin(), container.end(), function);
}
template <typename Container, typename Function>
void each_with_distance(Container container, Function function)
{
//The signature of the function should be equivalent to the following :
// void fun(const Type &a, const size_t d);
for (auto i = container.begin(); i != container.end(); ++i) {
function(*i, std::distance(container.begin(), i));
}
}
template <typename Container, typename Function>
void each_iter(Container container, Function function)
{
//The signature of the function should be equivalent to the following :
// void fun(const Type &a, const size_t d);
for (auto i = container.begin(); i != container.end(); ++i) {
function(i);
}
}
//template <class T, class = void>
//struct is_iterator : std::false_type { };
//template <class T>
//struct is_iterator<T, std::void_t<
// typename std::iterator_traits<T>::iterator_category
// >> : std::true_type { };
//template <typename T, typename Function>
//typename std::enable_if<is_iterator<T>::value, void>::type each_key_value(T iterator, Function function)
//{
// for (; iterator != container.end(); ++i) {
// auto key = i->first;
// auto value = i->second;
// function(value, key, container);
// }
//}
// The full power of `each`. Each invocation of iteratee is called
// with three arguments: (element, index, list). If list is an object,
// iteratee's arguments will be (value, key, list). (MDN)
template <typename Container, typename Function>
void each_key_value(Container container, Function function)
{
for (auto i = container.begin(); i != container.end(); ++i) {
auto key = i->first;
auto value = i->second;
function(value, key, container);
}
}
template <typename Iterator, typename Function>
void each_key_value(Iterator i, Iterator end, Function function)
{
for (; i != end; ++i) {
auto key = i->first;
auto value = i->second;
function(value, key);
}
}
// each - for nlohmann::json associative containers. iteratee has three arguments: (value, key, container).
template <typename Container, typename Function>
void each_json(Container& container, Function& function)
{
for (auto i = container.begin(); i != container.end(); ++i) {
auto key = i.key();
auto value = i.value();
function(value, key);
}
}
//template <typename Container, typename... Args>
//void each_json_magic(Container& container, std::function<void(Args...)> function)
//{
// auto iteratee = [](auto value, auto key, auto& container) {};
// switch (helper::count_arg<function>::value) {
// case 3: iteratee = [&] { function(value, key, container); }; break;
// case 2: iteratee = [&] { function(value, key); }; break;
// case 1: iteratee = [&] { function(value); }; break;
// }
// for (auto i = container.begin(); i != container.end(); ++i) {
// auto key = i.key();
// auto value = i.value();
// iteratee(value, key, container);
// }
//}
template <typename Container, typename Function>
void for_each(Container container, Function function)
{
each(container, function);
}
// map/collect
template <typename ResultContainer, typename Container, typename Function>
ResultContainer map(const Container& container, Function function)
{
ResultContainer result;
for (auto& item : container) helper::add_to_container(result, function(item));
//for (auto i = container.begin(); i != container.end(); ++i)
//{
// helper::add_to_container(result, function(*i));
//}
return result;
}
// map/collect with raw iterators -- sfink
template <typename ResultContainer, typename Container, typename Function>
ResultContainer map_iter(Container container, Function function)
{
ResultContainer result;
for (auto i = container.begin(); i != container.end(); ++i)
{
helper::add_to_container(result, function(i));
}
return result;
}
// mapObject - Creates an array of values by running each element in collection thru iteratee.
// The iteratee is invoked with two arguments: (value, key). -- sfink
template <typename ResultContainer, typename Container, typename Function>
ResultContainer mapObject(const Container& container, Function function)
{
ResultContainer result;
auto keys = keys(container);
for (const auto& key : keys)
helper::add_to_container(result, function(container[key], key));
return result;
}
// remove (lodash) - Removes all elements from array that predicate returns truthy for and returns an array of the removed elements.
// Note: Unlike _.filter, this method mutates array. Use _.pull to pull elements from an array by value.
// Note: for ease of use, this function does not return removed elements, use `removeAndReturn` instead
template <typename Container, typename Function>
void remove(Container& container, Function function) {
for ( auto i = container.begin(); i != container.end() ; )
function(*i) ? i = container.erase(i) : ++i;
}
// remove (lodash) - Removes all elements from array that predicate returns truthy for and returns an array of the removed elements.
// Note: Unlike _.filter, this method mutates array. Use _.pull to pull elements from an array by value.
template <typename ResultContainer, typename Container, typename Function>
ResultContainer removeAndReturn(Container& container, Function function) {
ResultContainer result;
for (auto i = container.begin(); i != container.end(); ) {
if (function(*i))
helper::add_to_container(result, *i),
i = container.erase(i);
else
++i;
}
return result;
}
// pull (lodash) - Removes all given values from array using SameValueZero for equality comparisons.
// Note: Unlike `without`, this method mutates array. Use _.remove to remove elements from an array by predicate.
template <typename Container>
void pull(Container& container, typename Container::value_type const& value)
{
for (auto i = container.begin(); i != container.end(); )
(*i == value) ? i = container.erase(i) : ++i;
}
// pullAll (lodash) - This method is like _.pull except that it accepts an array of values to remove.
// Note: Unlike _.difference, this method mutates array.
template <typename Container1, typename Container2>
void pullAll(Container1& container, Container2 const& values)
{
// Hmmm.... if it's similar to difference, maybe we could leverage the existing `difference` function...
// However, that function looks complicated. Lets leverage `contains` instead. It's possibly less
// efficient that using `difference` but simplicity wins today.
for (auto i = container.begin(); i != container.end(); )
contains(values, *i) ? i = container.erase(i) : ++i;
}
// filter/select
template <typename ResultContainer, typename Container, typename Predicate>
ResultContainer filter(Container container, Predicate predicate)
{
ResultContainer result;
for (auto i = container.begin(); i != container.end(); ++i)
{
if (predicate(*i))
{
helper::add_to_container(result, *i);
}
}
return result;
}
// without - Creates an array excluding all given values using SameValueZero for equality comparisons.
// Note: Unlike `pull`, this method returns a new array.
template <typename ResultContainer, typename Container>
ResultContainer without(Container const& container, typename Container::value_type const& value)
{
// sorry, you'll have to work out your own checks for C++17
return filter<ResultContainer>(container, [value](const auto& _) {
return value != _;
//return std::not_equal_to<typename Container::value_type>(_, value);
});
#if 0
// deprecated in c++11, removed in c++17
return filter<ResultContainer>(
container, std::bind2nd(std::not_equal_to<typename Container::value_type>(), value));
#endif
}
template <typename ResultContainer, typename Container, typename Function>
ResultContainer collect(Container container, Function function)
{
return map<ResultContainer>(container, function);
}
// sfink - values
template <typename ResultContainer, typename Container>
ResultContainer values(Container container)
{
ResultContainer result;
// zorg c++11 optimisation
for (const auto& item : container) helper::add_to_container(result, item);
// previously: (and still required for associative containers, e.g. map
// for (auto i = container.begin(); i != container.end(); ++i)
// {
// helper::add_to_container(result, *i);
// }
return result;
}
//template <class T, class Enable = void>
//class value_type_from
//{
// typedef T type;
//};
//template <class T>
//class value_type_from<T, typename enable_if_has_type<typename T::value_type>::type>
//{
// typedef typename T::value_type type;
//};
//typename Container::iterator
template <typename ResultContainer, typename Container>
ResultContainer valuesObject(Container container)
{
ResultContainer result;
for (auto i = container.begin(); i != container.end(); ++i)
{
auto value = i->second;
helper::add_to_container(result, value);
}
return result;
}
// sfink - keys
template <typename ResultContainer, typename Container>
ResultContainer keys(Container container)
{
ResultContainer result;
for (auto i = container.begin(); i != container.end(); ++i)
{
auto k = i->first;
helper::add_to_container(result, k);
}
//for (std::pair<std::string, std::string> i : container) {
// helper::add_to_container(result, i.first);
//}
return result;
}
template <typename ResultContainer, typename Container>
ResultContainer pairs(Container container)
{
ResultContainer result;
for (std::pair<std::string, std::string> i : container) {
helper::add_to_container(result, i.second);
}
return result;
}
// template <typename ResultContainer, typename Container, typename Function>
// typename helper::enable_if<!helper::is_void<ResultContainer>::value, ResultContainer>::type
//invoke(Container container, Function function)
// {
// sfink - keys_json
// template <typename ResultContainer, typename Container, typename Iterator Container::const_iterator>
template <typename ResultContainer, typename Container>
typename helper::enable_if<helper::HasJsonTraits<Container>::value, ResultContainer>::type
keys_json(Container container)
{
//json j;
//j.
ResultContainer result;
for (auto i = container.begin(); i != container.end(); ++i) {
helper::add_to_container(result, i.key());
}
for (std::pair<std::string, std::string> i : container) {
helper::add_to_container(result, i.first);
}
return result;
}
// sfink - keys2
template <typename Container>
auto keys2(const Container& container)
{
return keys<std::vector<typename Container::key_type>>(container);
//typename Container::key_type result;
//for (auto i = container.begin(); i != container.end(); ++i)
//{
// auto k = i->first;
// helper::add_to_container(result, k);
//}
//return result;
}
//template<class Iterator, typename = typename std::enable_if<is_pair<typename Iterator::value_type>::value, Iterator>::type>
//decltype(auto) do_stuff(Iterator&& iterator) {
// //access of iterator->second ok.
//}
template <typename T>
class HasJsonPointer
{
private:
typedef char yes[1];
typedef char no[2];
template <typename C>
static yes& test(typename C::json_pointer*);
template <typename C>
static no& test(...);
public:
static bool const value = sizeof(test<T>(0)) == sizeof(yes);
};
template <typename ResultContainer, typename Container>
typename helper::enable_if<!HasJsonPointer<typename Container::value_type>::value, void>::type
keys_internal(ResultContainer& result, Container const& container)
{
for (auto i = container.begin(); i != container.end(); ++i)
{
helper::add_to_container(result, *i);
}
}
template <typename ResultContainer, typename Container>
typename helper::enable_if<HasJsonPointer<typename Container::value_type>::value, void>::type
keys_internal(ResultContainer& result, Container const& container)
{
for (auto i = container.begin(); i != container.end(); ++i)
{
helper::add_to_container(result, *i);
}
}
// MDN - The slice() method returns a shallow copy of a portion of an array into a
// new array object selected from begin to end (end not included).
// The original array will not be modified.
template <typename ResultContainer, typename Container>
ResultContainer slice(Container container, long long begin = 0, long long end = 0)
{
//begin Optional
// Zero - based index at which to begin extraction.
// A negative index can be used, indicating an offset from the end of the sequence.slice(-2) extracts the last two elements in the sequence.
// If begin is undefined, slice begins from index 0.
//end Optional
// Zero - based index before which to end extraction.slice extracts up to but not including end.
// For example, slice(1, 4) extracts the second element through the fourth element(elements indexed 1, 2, and 3).
// A negative index can be used, indicating an offset from the end of the sequence.slice(2, -1) extracts the third element through the second - to - last element in the sequence.
// If end is omitted, slice extracts through the end of the sequence(arr.length).
// If end is greater than the length of the sequence, slice extracts through the end of the sequence(arr.length).
const size_t len = container.size();
if (end < 1)
end = len + end;
if (begin < 0)
begin = len + begin + 1;
begin = helper::clamp<long long>(begin, 0, len - 1);
end = helper::clamp<long long>(end, 0, len);
ResultContainer result;
long long _index = 0;
for (auto i = container.begin(); i != container.end(); ++i)
{
auto index = _index++;
if (index >= end)
break;
if (index >= begin)
helper::add_to_container(result, *i);
}
return result;
}
//Output:
// Index: 0 = 1
// Index : 1 = 2
// Index : 2 = 3
// reduce/inject/foldl
/// <summary>Applies a function against an accumulator and each element in the container (from left to right) to reduce it to a single value.</summary>
/// <param name="container">The container.</param>
/// <param name="function">The callback, callback(<paramref name="initialValue" />, currentValue, currentIndex, container)</param>
/// <param name="initialValue">Value to use as the first argument to the first call of the callback.</param>
/// <returns>The value that results from the reduction.</returns>
/// <example><code><![CDATA[
/// using fspath = std::experimental::filesystem::path;
/// template<typename Container>
/// std::string pathCombine(Container paths) {
/// fspath path = _::reduce(Container, [](fspath _path, std::string segment) {
/// return _path /= filepath(segment);
/// }, fspath);
/// return path.string();
/// }]]></code></example>
/// TODO Implement initialValue as optional: "[Optional] Value to use as the first argument to the first call of the callback. If no initial value is supplied, the first element in the array will be used. Calling reduce on an empty array without an initial value is an error."
/// TODO Implement full range of functionality as described in https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce?v=b
template <typename Container, typename Function, typename Memo>
Memo reduce(const Container& container, Function function, Memo initialValue)
{
each(container, [&](const auto& i) {
initialValue = function(initialValue, i);
});
//for (auto i = container.begin(); i != container.end(); ++i)
//{
// initialValue = function(initialValue, *i);
//}
return initialValue;
}
/// <summary>`reduce` for sequence containers with 4 argument callback</summary>
/// <param name="container">The container.</param>
/// <param name="function">callback(<paramref name="initialValue" />, currentValue, currentIndex, <paramref name="container" />)</param>
/// <param name="initialValue">Value to use as the first argument to the first call of the callback.</param>
/// <returns>The value that results from the reduction.</returns>
/// <example><code>
/// std::vector<int> v{ 1, 2, 3 };
/// count << _::reduceArray(v, [](auto accumulator, auto currentValue, auto currentIndex, auto container) {
/// return accumulator + "Index: "s + std::to_string(currentIndex) + " = "s + std::to_string(currentValue) + '\n';
/// }, std::string{})
/// </example></code>
/// TODO Implement initialValue as optional: "[Optional] Value to use as the first argument to the first call of the callback. If no initial value is supplied, the first element in the array will be used. Calling reduce on an empty array without an initial value is an error."
template <typename Container, typename Function, typename Memo>
Memo reduceArray(const Container& container, Function function, Memo initialValue)
{
each_with_distance(container, [&](const typename Container::value_type& value, const size_t index) {
initialValue = function(initialValue, value, index, container);
});
return initialValue;
}
/// <summary>`reduce` for associative containers with 4 argument callback</summary>
/// <see cref="reduce" />
/// <seealso cref="reduceArray" />
/// <param name="container">The container.</param>
/// <param name="function">callback(<paramref name="initialValue" />, currentValue, currentKey, <paramref name="container" />)</param>
/// <param name="initialValue">Value to use as the first argument to the first call of the callback.</param>
/// <returns>The value that results from the reduction.</returns>
/// TODO Implement initialValue as optional: "[Optional] Value to use as the first argument to the first call of the callback. If no initial value is supplied, the first element in the array will be used. Calling reduce on an empty array without an initial value is an error."
template <typename Container, typename Function, typename Memo>
Memo reduceObject(const Container& container, Function function, Memo initialValue)
{
// ResultContainer result;
auto keys = _::keys2(container);
for (const auto& key : keys)
{
// const auto& value = container.at(key);
auto value = container.at(key);
initialValue = function(initialValue, value, key, container);
}
return initialValue;
}
template <typename Container, typename Function, typename Memo>
Memo inject(const Container& container, Function function, Memo initialValue)
{
return reduce(container, function, initialValue);
}
template <typename Container, typename Function, typename Memo>
Memo foldl(const Container& container, Function function, Memo initialValue)
{
return reduce(container, function, initialValue);
}
// reduce_right/foldr
template <typename Container, typename Function, typename Memo>
Memo reduce_right(const Container& container, Function function, Memo initialValue)
{
for (typename Container::const_reverse_iterator i = container.rbegin(); i != container.rend();
++i)
{
initialValue = function(initialValue, *i);
}
return initialValue;
}
/// <summary>A copy of std::find_if</summary>
/// <param name="first">Iterator first.</param>
/// <param name="last">Iterator last.</param>
/// <param name="predicate">predicate</param>
/// <returns></returns>
template<class InputIterator, class UnaryPredicate>
InputIterator find_if(InputIterator first, InputIterator last, UnaryPredicate predicate)
{
while (first != last) {
if (predicate(*first)) return first;
++first;
}
return last;
}
template <typename Container, typename Function, typename Memo>
Memo foldr(const Container& container, Function function, Memo initialValue)
{
return reduce_right(container, function, initialValue);
}
// find/detect
/// <summary>Iterates over elements of collection, returning the first element predicate returns truthy for. The predicate is invoked with one argument: (value).</summary>
/// <param name="container">The container.</param>
/// <param name="predicate">The predicate.</param>
/// <returns></returns>
/// <remarks>This doesn't translate well into C++, as it should (by JavaScript underscore standards) return an actual element, or <c>undefined</c>. While we could simulate <c>undefined</c> with C++17 <c>std::optional</c> usage would not be more convenient that returning an iterator.
template <typename Container, typename Predicate>
typename Container::iterator find(Container& container, Predicate predicate)
{
return _::find_if(container.begin(), container.end(), predicate);
}
/// <summary>Iterates over elements of an associate collection, returning the first element predicate returns truthy for. The predicate is invoked with three arguments: (value, index|key, collection).</summary>
/// <param name="container">The container.</param>
/// <param name="predicate">The predicate (value, key, collection)</param>
/// <returns>The key of the first object found, or {}</returns>
template <typename Container, typename Function, typename Memo>
Memo findObject(const Container& container, Function predicate)
{
// ResultContainer result;
auto keys = _::keys2(container);
for (const auto& key : keys)
{
// const auto& value = container.at(key);
auto value = container.at(key);
auto found = function(value, key, container);
if (found)
return key;
}
return {};
}
template <typename ResultContainer, typename Container, typename Predicate>
ResultContainer select(Container container, Predicate predicate)
{
return filter<ResultContainer>(container, predicate);
}
// reject
template <typename ResultContainer, typename Container, typename Predicate>
ResultContainer reject(Container container, Predicate predicate)
{
ResultContainer result;
for (auto i = container.begin(); i != container.end(); ++i)
{
if (!predicate(*i))
{
helper::add_to_container(result, *i);
}
}
return result;
}
// all/every
template <typename Container, typename Predicate>
bool all(Container container, Predicate predicate)
{
for (auto i = container.begin(); i != container.end(); ++i)
{
if (!predicate(*i))
{
return false;
}
}
return true;
}
template <typename Container, typename Predicate>
bool every(Container container, Predicate predicate)
{
return all(container, predicate);
}
// any/some
template <typename Container, typename Predicate>
bool any(Container container, Predicate predicate)
{
for (auto i = container.begin(); i != container.end(); ++i)
{
if (predicate(*i))
{
return true;
}
}
return false;
}
template <typename Container, typename Predicate>
bool some(Container container, Predicate predicate)
{
return any(container, predicate);
}
// contains (alias includes)
template <typename Container>
bool contains(Container container, typename Container::value_type value)
{
return std::find(container.begin(), container.end(), value) != container.end();
}
template <typename Container>
bool includes(Container container, typename Container::value_type value)
{
return contains(container, value);
}
// invoke
template <typename ResultContainer, typename Container, typename Function>
typename helper::enable_if<!helper::is_void<ResultContainer>::value, ResultContainer>::type
invoke(Container container, Function function)
{
ResultContainer result;
for (typename Container::iterator i = container.begin(); i != container.end(); ++i)
{
helper::add_to_container(result, (*i.*function)());
}
return result;
}
template <typename ResultContainer, typename Container, typename Function>
typename helper::enable_if<helper::is_void<ResultContainer>::value, void>::type
invoke(Container container, Function function)
{
for (typename Container::iterator i = container.begin(); i != container.end(); ++i)
{
(*i.*function)();
}
}
// pluck
// Called like `_::pluck<vector<int>>(container, &value_type::member)`
template <typename ResultContainer, typename Container, typename Member>
ResultContainer pluck(Container const& container, Member member)
{
ResultContainer result;
for (auto i = container.begin(); i != container.end(); ++i)
{
helper::add_to_container(result, *i.*member);
}
return result;
}
/**
* The base implementation of `_.sum` and `_.sumBy` without support for
* iteratee shorthands.
*
* @private
* @param {Array} array The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {number} Returns the sum.
*/
template <typename Container, typename Function>
typename Container::value_type baseSum(Container array, Function iteratee) {
typename Container::value_type result = {};
for (const auto& i : array) {
auto current = iteratee(i);
result += current;
}
return result;
}
template<typename T>
constexpr auto identity(const T& _) {
return _;
}
/**
* Computes the sum of the values in `array`.
*
* @static
* @memberOf _
* @since 3.4.0
* @category Math
* @param {Array} array The array to iterate over.
* @returns {number} Returns the sum.
* @example
*
* _.sum([4, 2, 8, 6]);
* // => 20
*/
template <typename Container>
typename Container::value_type sum(Container container)
{
//return container.size() ? baseSum<Container>(container, identity) : 0;
return container.size() ? baseSum<Container>(container, _IDENTITY_LAMBDA) : 0;
}
// max
template <typename Container>
typename Container::iterator max(Container container)
{
if (container.begin() == container.end())
{
return container.end();
}
typename Container::iterator max = container.begin();
for (typename Container::iterator i = ++container.begin(); i != container.end(); ++i)