Skip to content

Commit 110a13a

Browse files
committed
refactor: optimize/cleanup
1 parent f80390f commit 110a13a

File tree

1 file changed

+12
-19
lines changed

1 file changed

+12
-19
lines changed

src/UnderscoreCollection.php

Lines changed: 12 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
namespace Ahc\Underscore;
44

5-
class UnderscoreCollection extends UnderscoreArray
5+
class UnderscoreCollection extends UnderscoreBase
66
{
77
public function each(callable $fn)
88
{
@@ -46,19 +46,19 @@ public function inject(callable $fn, $memo)
4646

4747
public function reduceRight(callable $fn, $memo)
4848
{
49-
return \array_reduce(\array_reverse($this->data), $fn, $memo);
49+
return \array_reduce(\array_reverse($this->data, true), $fn, $memo);
5050
}
5151

5252
public function foldr(callable $fn, $memo)
5353
{
5454
return $this->reduceRight($fn, $memo);
5555
}
5656

57-
public function find(callable $fn)
57+
public function find(callable $fn, $useValue = true)
5858
{
5959
foreach ($this->data as $index => $value) {
6060
if ($fn($value, $index)) {
61-
return $value;
61+
return $useValue ? $value : $index;
6262
}
6363
}
6464
}
@@ -68,8 +68,12 @@ public function detect(callable $fn)
6868
return $this->find($fn);
6969
}
7070

71-
public function filter(callable $fn)
71+
public function filter($fn = null)
7272
{
73+
if (null === $fn) {
74+
return new static(\array_filter($this->data));
75+
}
76+
7377
$data = \array_filter($this->data, $fn, \ARRAY_FILTER_USE_BOTH);
7478

7579
return new static($data);
@@ -247,23 +251,12 @@ protected function group($fn, $isGroup = true)
247251
$fn = $this->valueFn($fn);
248252

249253
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;
251255
}
252256

253257
return new static($data);
254258
}
255259

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-
267260
public function size()
268261
{
269262
return $this->count();
@@ -274,8 +267,8 @@ public function partition($fn)
274267
$data = [[/* pass */], [/* fail */]];
275268
$fn = $this->valueFn($fn);
276269

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;
279272
});
280273

281274
return new static($data);

0 commit comments

Comments
 (0)