Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Refactoring to Collections

Refactoring to Collections

A presentation inspired by Adam Wathan's book "Refactoring to Collections". Presented June 2nd, 2016 @ the Laravel Austin (@LaravelAustin)

Hunter Skrasek

June 02, 2016
Tweet

More Decks by Hunter Skrasek

Other Decks in Programming

Transcript

  1. HIGHER ORDER FUNCTIONS A function that takes another function as

    a parameter, returns a function, or does both. 2
  2. "Higher order functions are powerful because they let us create

    abstractions around common programming patterns" 3
  3. function each($items, $func) { for ($i = 0; $i <

    count($items); $i++) { $func($items[$i]); } } 8
  4. MAP Used to transform each item in an array into

    something else, creating a new array in the process. 9
  5. function map($items, $func) { $result = []; foreach ($items as

    $item) { $result[] = $func($item); } return $result; } 10
  6. function filter($items, $func) { $result = []; foreach ($items as

    $item) { if ($func($item)) { $result[] = $func($item); } } return $result; } 12
  7. REJECT A close cousin of filter, that simply flips the

    conditional to be more expressive. 13
  8. function reduce($items, $callback, $initial) { $accumulator = $initial; foreach ($items

    as $item) { $accumulator = $callback($accumulator, $item); } return $accumulator; } 15
  9. function map($items, $func) { return reduce($items, function ($mapped, $item) use

    ($func) { $mapped[] = $func($item); return $mapped; }); } 17
  10. THINKING IN STEPS Break a problem into many steps. Turn

    "I can't because..." into "I could if..." 18
  11. THE PROBLEM WITH PRIMITIVES We have to operate on them

    from the outside by passing them as parameters into other functions. 19