Skip to content

Instantly share code, notes, and snippets.

@SebSept
Last active March 15, 2020 10:39
Show Gist options
  • Save SebSept/dcbf0faf002fb0f8ec2779f2dc5123ac to your computer and use it in GitHub Desktop.
Save SebSept/dcbf0faf002fb0f8ec2779f2dc5123ac to your computer and use it in GitHub Desktop.
php functionnal playground
<?php
/**
* playground
*
* functionnal use is at the bottom.
*
* Don't damn me, that's a playground.
*/
class Pipe {
private $data;
public function __construct($data)
{
$this->data = $data;
}
public static function from($data): Pipe
{
$instance = new static($data);
$instance->data = $data;
return $instance;
}
public function map(callable $map_function)
{
return static::from(array_map($map_function, $this->data));
}
public function getData()
{
return $this->data;
}
public function filter(callable $fn)
{
return static::from(array_filter($this->data, $fn));
}
public function reduce(callable $fn)
{
return static::from(array_reduce($this->data, $fn, 0) );
}
public function call(callable $fn)
{
return static::from( call_user_func($fn, $this->data) );
}
public function repeat(callable $fn, int $times = 1, int $delay = 0)
{
if($times < 1) {
return static::from($this->data);
}
sleep($delay);
return static::call($fn,$this->data)->repeat($fn, $times-1, $delay);
}
public function dump(string $text_before = '')
{
echo PHP_EOL.$text_before.PHP_EOL;
var_dump($this->data);
return static::from( $this->data );
}
}
$data = range(0,12,2);
$plus1 = function (int $a):int { return $a+1; };
$to_hex= function (int $a):string { return decbin($a); };
$greater = function (int $max): Closure {
return function(int $num) use ($max):bool {
return ($num > $max);
};
};
$sum = function (int $result, int $current = 0):int { return $result+$current;};
$append_to_array = function($to_append) {
return function (array $array) use($to_append):array {
array_push($array, $to_append);
return $array;
};
};
$transformed_data = Pipe::from($data)
->map($plus1)
->map($to_hex)
->map('crc32')
->filter($greater(2212294583))
->dump("after filter")
->call($append_to_array("666"))
->dump("added 666")
->repeat($append_to_array("777"), 3)
->dump()
->reduce($sum)
->getData();
var_dump($transformed_data);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment