Created
December 5, 2022 12:54
-
-
Save thgs/52c629e109c6daefc2cc81bc7943cdea to your computer and use it in GitHub Desktop.
Flip Flop example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function flipFlop2(): \Generator | |
{ | |
$switch = false; | |
while (true) { | |
$value = yield; | |
// condition1 | |
if ($value == 1) { | |
$switch = true; | |
} | |
yield $switch; | |
// condition2 | |
if ($value == 1) { | |
$switch = false; | |
} | |
} | |
} | |
function flipFlop3(): \Generator | |
{ | |
$switch = false; | |
while (true) { | |
$value = yield; | |
// condition1 | |
if ($value == 1) { | |
$switch = true; | |
yield $switch; | |
// condition2 | |
} elseif ($value == 1) { | |
$result = $switch; | |
$switch = false; | |
yield $result; | |
// none of the two match | |
} else { | |
yield $switch; | |
} | |
} | |
} | |
$a = range(1, 4); | |
$example = [1,2,3,4,5,6,3,7]; | |
$a = $example; | |
$flipFlop2 = flipFlop2(); | |
$flipFlop3 = flipFlop3(); | |
$result = []; | |
foreach ($a as $i) { | |
if ($return = $flipFlop3->send($i)) { | |
$result[] = $i; | |
} | |
echo "$i => " . ($return ? 'true' : 'false') . "\n"; | |
$flipFlop3->next(); | |
} | |
print_r($result); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment