Skip to content

Commit dc54d1f

Browse files
committed
feat: add underscore array class
1 parent 1f14309 commit dc54d1f

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

src/UnderscoreArray.php

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
<?php
2+
3+
namespace Ahc\Underscore;
4+
5+
class UnderscoreArray extends UnderscoreBase
6+
{
7+
public function first()
8+
{
9+
return \reset($this->data);
10+
}
11+
12+
public function last()
13+
{
14+
return \end($this->data);
15+
}
16+
17+
public function compact()
18+
{
19+
return new static(\array_filter($this->data));
20+
}
21+
22+
public function flatten()
23+
{
24+
return new static($this->flat($this->data));
25+
}
26+
27+
public function unique($fn = null)
28+
{
29+
if (null === $fn) {
30+
return new static(\array_unique($this->data));
31+
}
32+
33+
$ids = $data = [];
34+
$fn = $this->valueFn($fn);
35+
36+
foreach ($this->data as $index => $value) {
37+
if (!isset($ids[$id = $fn($value, $index)])) {
38+
$ids[$id] = true;
39+
40+
$data[$index] = $value;
41+
}
42+
}
43+
44+
return new static($data);
45+
}
46+
47+
public function uniq($fn)
48+
{
49+
return $this->unique($fn);
50+
}
51+
}

0 commit comments

Comments
 (0)