Created
March 15, 2014 16:21
-
-
Save aurelijusb/9569894 to your computer and use it in GitHub Desktop.
State based sumation to callback based sumation 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 | |
require 'context.php'; | |
$odd = array_flip(array_filter(array_flip($pairs), | |
function($key) { return $key % 2 == 0; } | |
)); | |
$even = array_diff($pairs, $odd); | |
$sumOdd = array_reduce($odd, Summation::$fSum); | |
$sumEven = array_reduce($even, ['Summation', 'rSum']); | |
$sumAll = array_reduce($pairs, [new Summation(), 'rightSum']); | |
var_dump($sumOdd, $sumEven, $sumAll); | |
$withVat = array_map( | |
function ($price) { return vatGeneral($price, 21); }, | |
$pairs); | |
$sumWithVat = array_reduce($withVat, 'Summation::rSum'); | |
var_dump($withVat, $sumWithVat); |
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 | |
class Summation { // array_sum alternative | |
static $fSum = null; | |
static function rSum($aggregated, $current) { | |
return $aggregated + $current; | |
} | |
function rightSum($aggregated, $current) { | |
return self::rSum($aggregated, $current); | |
} | |
} | |
Summation::$fSum = function($aggregated, $current) { | |
return Summation::rSum($aggregated, $current); | |
}; | |
function vatGeneral($price, $vat) { | |
return $price * (1+$vat/100); | |
} | |
$pairs = (array) json_decode('{"1":10,"2":5,"3":8,"4":1}'); |
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 | |
require 'context.php'; | |
$sumOdd = 0; $sumEven = 0; $sumAll = 0; | |
$sumWithVat = 0; | |
$withVat = array(); | |
foreach ($pairs as $name => $price) { | |
if ($price % 2 == 0) { | |
$sumOdd += $price; | |
} else { | |
$sumEven += $price; | |
} | |
$sumAll += $price; | |
$priceWithVat = vatGeneral($price, 21); | |
$sumWithVat += $priceWithVat; | |
$withVat[$name] = $priceWithVat; | |
} | |
var_dump($sumOdd, $sumEven, $sumAll); | |
var_dump($withVat, $sumWithVat); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment