2
2
3
3
namespace Ahc \Underscore ;
4
4
5
- class UnderscoreArray extends UnderscoreBase
5
+ class UnderscoreArray extends UnderscoreCollection
6
6
{
7
- public function first ()
7
+ public function first ($ n = 1 )
8
8
{
9
- return \reset ( $ this ->data );
9
+ return $ this ->slice ( $ n , true );
10
10
}
11
11
12
- public function last ( )
12
+ public function head ( $ n = 1 )
13
13
{
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 );
15
48
}
16
49
17
50
public function compact ()
@@ -33,18 +66,12 @@ public function unique($fn = null)
33
66
$ ids = $ data = [];
34
67
$ fn = $ this ->valueFn ($ fn );
35
68
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
+ });
45
72
}
46
73
47
- public function uniq ($ fn )
74
+ public function uniq ($ fn = null )
48
75
{
49
76
return $ this ->unique ($ fn );
50
77
}
0 commit comments