Link
Embed
Share
Beginning
This slide
Copy link URL
Copy link URL
Copy iframe embed code
Copy iframe embed code
Copy javascript embed code
Copy javascript embed code
Share
Tweet
Share
Tweet
Slide 1
Slide 1 text
REFACTORING TO COLLECTIONS 1
Slide 2
Slide 2 text
HIGHER ORDER FUNCTIONS A function that takes another function as a parameter, returns a function, or does both. 2
Slide 3
Slide 3 text
"Higher order functions are powerful because they let us create abstractions around common programming patterns" 3
Slide 4
Slide 4 text
FUNCTIONAL BUILDING BLOCKS 4
Slide 5
Slide 5 text
EACH No more than a foreach loop wrapped inside of a higher order function. 5
Slide 6
Slide 6 text
function each($items, $func) { foreach ($items as $item) { $func($item); } } 6
Slide 7
Slide 7 text
Imagine a world without a foreach loop 7
Slide 8
Slide 8 text
function each($items, $func) { for ($i = 0; $i < count($items); $i++) { $func($items[$i]); } } 8
Slide 9
Slide 9 text
MAP Used to transform each item in an array into something else, creating a new array in the process. 9
Slide 10
Slide 10 text
function map($items, $func) { $result = []; foreach ($items as $item) { $result[] = $func($item); } return $result; } 10
Slide 11
Slide 11 text
FILTER Used to filter out any elements of an array that you don't want. 11
Slide 12
Slide 12 text
function filter($items, $func) { $result = []; foreach ($items as $item) { if ($func($item)) { $result[] = $func($item); } } return $result; } 12
Slide 13
Slide 13 text
REJECT A close cousin of filter, that simply flips the conditional to be more expressive. 13
Slide 14
Slide 14 text
REDUCE Used to take some array of items and reduce it down to a single value. 14
Slide 15
Slide 15 text
function reduce($items, $callback, $initial) { $accumulator = $initial; foreach ($items as $item) { $accumulator = $callback($accumulator, $item); } return $accumulator; } 15
Slide 16
Slide 16 text
Speaking of patterns.... 16
Slide 17
Slide 17 text
function map($items, $func) { return reduce($items, function ($mapped, $item) use ($func) { $mapped[] = $func($item); return $mapped; }); } 17
Slide 18
Slide 18 text
THINKING IN STEPS Break a problem into many steps. Turn "I can't because..." into "I could if..." 18
Slide 19
Slide 19 text
THE PROBLEM WITH PRIMITIVES We have to operate on them from the outside by passing them as parameters into other functions. 19
Slide 20
Slide 20 text
$camelString = lcfirst( str_replace(' ', '', ucwords(str_replace('_', ' ', $snakeString)) ) ); 20
Slide 21
Slide 21 text
$camelString = $snakeString->replace('_', ' ') ->ucwords() ->replace(' ', '') ->lcfirst(); 21
Slide 22
Slide 22 text
PRACTICE 22