Skip to content

Commit 27f815e

Browse files
committed
refactor: quantify first() last() and add aliases
1 parent 4f8bcfc commit 27f815e

File tree

1 file changed

+42
-15
lines changed

1 file changed

+42
-15
lines changed

src/UnderscoreArray.php

Lines changed: 42 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -2,16 +2,49 @@
22

33
namespace Ahc\Underscore;
44

5-
class UnderscoreArray extends UnderscoreBase
5+
class UnderscoreArray extends UnderscoreCollection
66
{
7-
public function first()
7+
public function first($n = 1)
88
{
9-
return \reset($this->data);
9+
return $this->slice($n, true);
1010
}
1111

12-
public function last()
12+
public function head($n = 1)
1313
{
14-
return \end($this->data);
14+
return $this->first($n);
15+
}
16+
17+
public function take($n = 1)
18+
{
19+
return $this->first($n);
20+
}
21+
22+
public function last($n = 1)
23+
{
24+
return $this->slice($n, false);
25+
}
26+
27+
public function tail($n = 1)
28+
{
29+
return $this->last($n);
30+
}
31+
32+
public function drop($n = 1)
33+
{
34+
return $this->last($n);
35+
}
36+
37+
protected function slice($n, $isFirst = true)
38+
{
39+
if ($n < 2) {
40+
return $isFirst ? \reset($this->data) : \end($this->data);
41+
}
42+
43+
if ($n >= $c = $this->count()) {
44+
return $this->data;
45+
}
46+
47+
return \array_slice($this->data, $isFirst ? 0 : $c - $n, $isFirst ? $n : null, true);
1548
}
1649

1750
public function compact()
@@ -33,18 +66,12 @@ public function unique($fn = null)
3366
$ids = $data = [];
3467
$fn = $this->valueFn($fn);
3568

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);
69+
return $this->filter(function ($value, $index) use ($fn, &$ids) {
70+
return !isset($ids[$id = $fn($value, $index)]) ? $ids[$id] = true : false;
71+
});
4572
}
4673

47-
public function uniq($fn)
74+
public function uniq($fn = null)
4875
{
4976
return $this->unique($fn);
5077
}

0 commit comments

Comments
 (0)