-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathCollection.php
76 lines (57 loc) · 1.23 KB
/
Collection.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
<?php
/**
* A simple wrapper arround arrays to provide a more expressive syntax.
*/
class Collection {
public static function fromArray($array){
$collection = new Collection($array);
return $collection;
}
private function __construct($value){
$this->value = $value;
}
public function map(){
$args = func_get_args();
foreach($args as &$fn){
$this->value = array_map($fn,$this->value);
}
return $this;
}
public function filter($fn){
$this->value = array_filter($this->value,$fn);
return $this;
}
public function reduce($fn,$mem = null){
return array_reduce($this->value,$fn,$mem);
}
public function withEach($fn){
array_walk($this->value,$fn);
return $this;
}
public function start($fn){
if(count($this->value) > 0){
$this->value[0] = $fn($this->value[0]);
}
return $this;
}
public function end($fn){
$length = count($this->value);
if($length){
$this->value[$length - 1] = $fn($this->value[$length - 1]);
}
return $this;
}
public function sort($fn){
usort($this->value,$fn);
return $this;
}
public function count(){
return count($this->value);
}
public function value(){
return $this->value;
}
public function isEmpty(){
return count($this->value) == 0;
}
}