Skip to content

Commit 58372dc

Browse files
committed
feat+fix: add where(), fix typo
1 parent b3feb2b commit 58372dc

File tree

1 file changed

+30
-6
lines changed

1 file changed

+30
-6
lines changed

src/Underscore.php

Lines changed: 30 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,7 @@ public function foldr(callable $fn, $memo)
9494
public function find(callabe $fn)
9595
{
9696
foreach ($this->data as $index => $value) {
97-
if ($fn($value, $key)) {
97+
if ($fn($value, $index)) {
9898
return $value;
9999
}
100100
}
@@ -190,15 +190,34 @@ public function invoke(callable $fn)
190190

191191
public function pluck($columnKey, $indexKey = null)
192192
{
193-
if (\function_exists('array_column')) {
194-
$data = \array_column($this->data, $columnKey, $indexKey);
195-
} else {
196-
$data = Helper::arrayColumn($this->data, $columnKey, $indexKey);
197-
}
193+
$data = \array_column($this->data, $columnKey, $indexKey);
198194

199195
return new static($data);
200196
}
201197

198+
public function where(array $props)
199+
{
200+
return $this->filter($this->matcher($props));
201+
}
202+
203+
public function findWhere(array $props)
204+
{
205+
return $this->find($this->matcher($props));
206+
}
207+
208+
protected function matcher(array $props)
209+
{
210+
return function ($value, $index) use ($props) {
211+
foreach ($props as $prop => $criteria) {
212+
if ($value !== $criteria || $prop != $index) {
213+
return false;
214+
}
215+
}
216+
217+
return true;
218+
};
219+
}
220+
202221
/**
203222
* {@inheritdoc}
204223
*/
@@ -262,6 +281,11 @@ public function __toString()
262281
{
263282
return \json_encode($this->data);
264283
}
284+
285+
public static function _($data)
286+
{
287+
return new static($data);
288+
}
265289
}
266290

267291
\class_alias('Ahc\Underscore\Underscore', 'Ahc\Underscore');

0 commit comments

Comments
 (0)