diff --git a/src/Collection.php b/src/Collection.php new file mode 100644 index 0000000..9711ba8 --- /dev/null +++ b/src/Collection.php @@ -0,0 +1,86 @@ +elements = $elements; + } + + public function first(): mixed + { + return reset($this->elements); + } + + public function last(): mixed + { + return end($this->elements); + } + + public function count(): int + { + return count($this->elements); + } + + public function clear(): bool + { + $this->elements = []; + return count($this->elements) == 0; + } + + public function reduce(callable $fn, mixed $initial): mixed + { + return array_reduce($this->elements, $fn, $initial); + } + + public function map(callable $fn): Collection + { + $tmp = array_map($fn, $this->elements); + return new Collection($tmp); + } + + public function each(callable $fn): void + { + array_walk($this->elements, $fn); + } + + public function filter(callable $fn): Collection + { + $tmp = array_filter($this->elements, $fn, ARRAY_FILTER_USE_BOTH); + $collect = new Collection($tmp); + return $collect; + } + + public function empty(): bool + { + return empty($this->elements); + } + + public function add(mixed $element): void + { + $this->elements[] = $element; + } + + public function values(): array + { + return array_values($this->elements); + } + + public function items(): array + { + return $this->elements; + } + + public function getIterator(): Traversable + { + return new ArrayIterator($this->elements); + } +} diff --git a/tests/CollectionTest.php b/tests/CollectionTest.php new file mode 100644 index 0000000..afe80ac --- /dev/null +++ b/tests/CollectionTest.php @@ -0,0 +1,52 @@ +toBe(11); + + $coll = new Collection($arr); + expect($coll->count())->toBe(11); + expect($coll->first())->toBe(0); + expect($coll->last())->toBe(10); + + $filt = $coll->filter(function($item){ return $item<5;}); + expect($filt)->toBeInstanceOf(Collection::class); + expect($filt->count())->toBe(5); + expect($filt->first())->toBe(0); + expect($filt->last())->toBe(4); + + // no change in initial collection + expect($coll->count())->toBe(11); + + expect($coll->empty())->toBe(false); + + expect($coll->items())->toBeArray(); + expect(count($coll->items()))->toBe(11); + + $incr = 0; + $coll->each(function($item) use(&$incr){ + $incr++; + }); + expect($incr)->toBe(11); + + $colmap = $coll->map(function($item) { + return $item+1; + }); + expect($colmap)->toBeInstanceOf(Collection::class); + expect($colmap->count())->toBe(11); + expect($colmap->first())->toBe(1); + expect($colmap->last())->toBe(11); + + $init = 0; + $reduce = $coll->reduce(function($item,$carry){ + return $item + $carry; + },$init); + expect($reduce)->toBe(55); +}); + \ No newline at end of file