Skip to content

Commit

Permalink
Fix the behavior of the ::apply() operation.
Browse files Browse the repository at this point in the history
  • Loading branch information
drupol committed Jan 8, 2020
1 parent bc2d733 commit eb1c4ae
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 85 deletions.
89 changes: 11 additions & 78 deletions spec/loophp/collection/CollectionSpec.php
Original file line number Diff line number Diff line change
Expand Up @@ -57,16 +57,20 @@ public function it_can_apply(): void
->shouldIterateAs($input);

$this
->apply(static function ($item) {
return $item;
})
->apply(
static function ($item) {
return $item;
}
)
->shouldIterateAs($input);

$this
->apply(static function ($item) {
return false;
})
->shouldReturnAnInstanceOf(\loophp\collection\Contract\Collection::class);
->apply(
static function ($item) {
return false;
}
)
->shouldReturnAnInstanceOf(Collection::class);

$callback = static function (): void {
throw new Exception('foo');
Expand All @@ -76,77 +80,6 @@ public function it_can_apply(): void
->apply($callback)
->shouldThrow(Exception::class)
->during('all');

$context = [];

$applyCallback1 = static function ($item, $key) use (&$context) {
if (3 > $item) {
$context[] = 0;

return 0;
}

if (3 <= $item && 6 > $item) {
$context[] = true;

return true;
}

if (9 < $item) {
$context[] = 'nine';

return false;
}

$context[] = $item;
};

$walkCallback2 = static function ($item) {
if (3 > $item) {
return 0;
}

if (3 <= $item && 6 > $item) {
return true;
}

if (10 === $item) {
return 'nine';
}

if (10 < $item) {
return false;
}

return $item;
};

$this::with(range(1, 20))
->apply($applyCallback1)
->walk($walkCallback2)
->filter(static function ($item) {
return false !== $item;
})
->all()
->shouldIterateAs($context);

$context = [];

$applyCallback1 = static function ($item, $key) use (&$context) {
$context[] = $item;

return true;
};

$walkCallback2 = static function ($item) {
return $item;
};

$this::with(range(1, 20))
->apply($applyCallback1)
->walk($walkCallback2)
->all()
->shouldIterateAs($context);
}

public function it_can_be_constructed_from_array(): void
Expand Down
12 changes: 5 additions & 7 deletions src/Operation/Apply.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,15 +36,13 @@ public function on(iterable $collection): Closure
$callbacks = $this->callbacks;

return static function () use ($callbacks, $collection): Generator {
foreach ($callbacks as $callback) {
foreach ($collection as $key => $value) {
if (false === $callback($value, $key)) {
break;
}
foreach ($collection as $key => $value) {
foreach ($callbacks as $callback) {
$callback($value, $key);
}
}

yield from $collection;
yield $key => $value;
}
};
}
}

0 comments on commit eb1c4ae

Please sign in to comment.