Skip to content

Instantly share code, notes, and snippets.

@sergiors
Last active April 17, 2017 05:52
Show Gist options
  • Save sergiors/4d00b0184ae08143cec2c4192256881c to your computer and use it in GitHub Desktop.
Save sergiors/4d00b0184ae08143cec2c4192256881c to your computer and use it in GitHub Desktop.
Reduce seu novo melhor amigo (Exemplos PHP)
<?php
function every($fn, $ls)
{
$keys = array_keys($ls);
$params = (new \ReflectionFunction($fn))->getParameters();
return array_reduce($keys, function ($carry, $idx) use ($fn, $ls, $params) {
$args = $ls[$idx];
if (isset($params[1])) {
$carry[$idx] = call_user_func_array($fn, [$idx, $args]);
return $carry;
}
$carry[$idx] = $fn($args);
return $carry;
}, []);
}
function sum($ls)
{
return array_reduce($ls, function ($carry, $item) {
return $carry + $item;
}, 0);
}
function pipe()
{
$ls = func_get_args();
return array_reduce($ls, function ($carry, $fn) {
if (is_null($carry)) {
return $fn;
}
return function () use ($carry, $fn) {
$args = func_get_args();
return $fn(call_user_func_array($carry, $args));
};
});
}
function compose()
{
$args = func_get_args();
return call_user_func_array('pipe', array_reverse($args));
}
function flatten($ls)
{
if ($ls instanceof \ArrayIterator) {
$ls = flatten($ls->getArrayCopy());
}
return array_reduce($ls, function ($carry, $item) {
if (is_array($item) || $item instanceof \ArrayIterator) {
return array_merge($carry, flatten($item));
}
$carry[] = $item;
return $carry;
}, []);
}
function map($fn, $ls)
{
return array_reduce($ls, function ($carry, $item) use ($fn) {
$carry[] = $fn($item);
return $carry;
}, []);
}
function filter($fn, $ls)
{
return array_reduce($ls, function ($carry, $item) use ($fn) {
if ($fn($item)) {
$carry[] = $item;
return $carry;
}
return $carry;
}, []);
}
<?php
$inc = function ($x) {
return $x + 1;
};
$odd = function ($x) {
return $x & 1;
};
$even = function ($x) {
return !($x & 1);
};
$plus2 = function ($x) {
return $x + 2;
};
$times4 = function ($x) {
return $x * 4;
};
assert(map($inc, [1, 2, 3, 4, 5, 6, 7, 8, 9]) === [2, 3, 4, 5, 6, 7, 8, 9, 10]);
assert(filter($odd, [1, 2, 3, 4, 5, 6, 7, 8]) === [1, 3, 5, 7]);
assert(filter($even, [1, 2, 3, 4, 5, 6, 7, 8]) === [2, 4, 6, 8]);
assert(flatten([[[1, [1.1]], 2, 3], [4, 5]]) === [1, 1.1, 2, 3, 4, 5]);
assert(flatten([1, [2,3], [4,[5,[6]]]]) === [1, 2, 3, 4, 5, 6]);
assert(map(compose($plus2, $times4), [1, 2, 5, 8]) === [12, 16, 28, 40]);
assert(pipe(function ($arr) {
$arr[] = 'b';
return $arr;
}, function ($arr) {
$arr[] = 'c';
return $arr;
})(['a']) === ['a', 'b', 'c']);
assert(pipe(function ($ls) {
return filter(function ($x) {
return $x & 1;
}, $ls);
}, function ($ls) {
return map(function ($x) {
return $x * 10;
}, $ls);
}, 'sum')([1, 2, 3, 4, 5]) === 90);
assert(pipe('deg2rad', 'cos')(360) === 1.0); // avoid cos(deg2rad(360));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment