A presentation inspired by Adam Wathan's book "Refactoring to Collections". Presented June 2nd, 2016 @ the Laravel Austin (@LaravelAustin)
REFACTORING TOCOLLECTIONS1
View Slide
HIGHER ORDER FUNCTIONSA function that takes another function as a parameter, returns afunction, or does both.2
"Higher order functions are powerful because they let us createabstractions around common programming patterns"3
FUNCTIONAL BUILDING BLOCKS4
EACHNo more than a foreach loop wrapped inside of a higher orderfunction.5
function each($items, $func){foreach ($items as $item) {$func($item);}}6
Imagine a world without a foreach loop7
function each($items, $func){for ($i = 0; $i < count($items); $i++) {$func($items[$i]);}}8
MAPUsed to transform each item in an array into something else, creating anew array in the process.9
function map($items, $func){$result = [];foreach ($items as $item) {$result[] = $func($item);}return $result;}10
FILTERUsed to filter out any elements of an array that you don't want.11
function filter($items, $func){$result = [];foreach ($items as $item) {if ($func($item)) {$result[] = $func($item);}}return $result;}12
REJECTA close cousin of filter, that simply flips the conditional to be moreexpressive.13
REDUCEUsed to take some array of items and reduce it down to a single value.14
function reduce($items, $callback, $initial){$accumulator = $initial;foreach ($items as $item) {$accumulator = $callback($accumulator, $item);}return $accumulator;}15
Speaking of patterns....16
function map($items, $func){return reduce($items, function ($mapped, $item) use ($func) {$mapped[] = $func($item);return $mapped;});}17
THINKING IN STEPSBreak a problem into many steps. Turn "I can't because..." into "I couldif..."18
THE PROBLEM WITH PRIMITIVESWe have to operate on them from the outside by passing them asparameters into other functions.19
$camelString = lcfirst(str_replace(' ', '',ucwords(str_replace('_', ' ', $snakeString))));20
$camelString = $snakeString->replace('_', ' ')->ucwords()->replace(' ', '')->lcfirst();21
PRACTICE22