2
2
3
3
namespace Ahc \Underscore ;
4
4
5
- class UnderscoreCollection extends UnderscoreArray
5
+ class UnderscoreCollection extends UnderscoreBase
6
6
{
7
7
public function each (callable $ fn )
8
8
{
@@ -46,19 +46,19 @@ public function inject(callable $fn, $memo)
46
46
47
47
public function reduceRight (callable $ fn , $ memo )
48
48
{
49
- return \array_reduce (\array_reverse ($ this ->data ), $ fn , $ memo );
49
+ return \array_reduce (\array_reverse ($ this ->data , true ), $ fn , $ memo );
50
50
}
51
51
52
52
public function foldr (callable $ fn , $ memo )
53
53
{
54
54
return $ this ->reduceRight ($ fn , $ memo );
55
55
}
56
56
57
- public function find (callable $ fn )
57
+ public function find (callable $ fn, $ useValue = true )
58
58
{
59
59
foreach ($ this ->data as $ index => $ value ) {
60
60
if ($ fn ($ value , $ index )) {
61
- return $ value ;
61
+ return $ useValue ? $ value : $ index ;
62
62
}
63
63
}
64
64
}
@@ -68,8 +68,12 @@ public function detect(callable $fn)
68
68
return $ this ->find ($ fn );
69
69
}
70
70
71
- public function filter (callable $ fn )
71
+ public function filter ($ fn = null )
72
72
{
73
+ if (null === $ fn ) {
74
+ return new static (\array_filter ($ this ->data ));
75
+ }
76
+
73
77
$ data = \array_filter ($ this ->data , $ fn , \ARRAY_FILTER_USE_BOTH );
74
78
75
79
return new static ($ data );
@@ -247,23 +251,12 @@ protected function group($fn, $isGroup = true)
247
251
$ fn = $ this ->valueFn ($ fn );
248
252
249
253
foreach ($ this ->data as $ index => $ value ) {
250
- $ isGroup ? $ data [$ fn ($ value )][$ index ] = $ value : $ data [$ fn ($ value )] = $ value ;
254
+ $ isGroup ? $ data [$ fn ($ value, $ index )][$ index ] = $ value : $ data [$ fn ($ value, $ index )] = $ value ;
251
255
}
252
256
253
257
return new static ($ data );
254
258
}
255
259
256
- public function toArray ()
257
- {
258
- return $ this ->map (function ($ value ) {
259
- if (\is_scalar ($ value )) {
260
- return $ value ;
261
- }
262
-
263
- return $ this ->asArray ($ value );
264
- })->get ();
265
- }
266
-
267
260
public function size ()
268
261
{
269
262
return $ this ->count ();
@@ -274,8 +267,8 @@ public function partition($fn)
274
267
$ data = [[/* pass */ ], [/* fail */ ]];
275
268
$ fn = $ this ->valueFn ($ fn );
276
269
277
- $ this ->each (function ($ value , $ key ) use ($ fn , &$ data ) {
278
- $ data [$ fn ($ value , $ key ) ? 0 : 1 ][] = $ value ;
270
+ $ this ->each (function ($ value , $ index ) use ($ fn , &$ data ) {
271
+ $ data [$ fn ($ value , $ index ) ? 0 : 1 ][] = $ value ;
279
272
});
280
273
281
274
return new static ($ data );
0 commit comments