| 1 | <?php |
||
| 12 | class GroupingFlightsTest extends PHPUnit_Framework_TestCase |
||
| 13 | { |
||
| 14 | private $inputData = [ |
||
| 15 | [ |
||
| 16 | "origin" => "BOS", |
||
| 17 | "dest" => "LAX", |
||
| 18 | "date" => "2015-01-12", |
||
| 19 | "number" => "25", |
||
| 20 | "carrier" => "AA", |
||
| 21 | "delay" => 10.0, |
||
| 22 | "cancelled" => false |
||
| 23 | ], |
||
| 24 | [ |
||
| 25 | "origin" => "BOS", |
||
| 26 | "dest" => "LAX", |
||
| 27 | "date" => "2015-01-13", |
||
| 28 | "number" => "25", |
||
| 29 | "carrier" => "AA", |
||
| 30 | "delay" => 0.0, |
||
| 31 | "cancelled" => true |
||
| 32 | ], |
||
| 33 | ]; |
||
| 34 | |||
| 35 | public function testIt() |
||
| 36 | { |
||
| 37 | $collection = new Collection($this->inputData); |
||
| 38 | |||
| 39 | $result = $collection |
||
| 40 | ->groupBy(function ($v) { |
||
| 41 | return $v['dest']; |
||
| 42 | }) |
||
| 43 | ->map([$this, 'summarize']) |
||
| 44 | ->map([$this, 'buildResults']) |
||
| 45 | ->toArray(); |
||
| 46 | |||
| 47 | $expected = [ |
||
| 48 | 'LAX' => [ |
||
| 49 | 'meanDelay' => 10, |
||
| 50 | 'cancellationRate' => 0.5 |
||
| 51 | ] |
||
| 52 | ]; |
||
| 53 | |||
| 54 | $this->assertEquals($expected, $result); |
||
| 55 | } |
||
| 56 | |||
| 57 | public function summarize(Collection $flights) |
||
| 58 | { |
||
| 59 | $numCancellations = $flights |
||
| 60 | ->filter(function ($f) { |
||
| 61 | return $f['cancelled']; |
||
| 62 | }) |
||
| 63 | ->size(); |
||
| 64 | |||
| 65 | $totalDelay = $flights |
||
| 66 | ->reject(function ($f) { |
||
| 67 | return $f['cancelled']; |
||
| 68 | }) |
||
| 69 | ->reduce( |
||
| 70 | function ($tmp, $f) { |
||
| 71 | return $tmp + $f['delay']; |
||
| 72 | }, |
||
| 73 | 0 |
||
| 74 | ); |
||
| 75 | |||
| 76 | return [ |
||
| 77 | 'numFlights' => $flights->size(), |
||
| 78 | 'numCancellations' => $numCancellations, |
||
| 79 | 'totalDelay' => $totalDelay |
||
| 80 | ]; |
||
| 81 | } |
||
| 82 | |||
| 83 | public function buildResults(array $airport) |
||
| 84 | { |
||
| 85 | return [ |
||
| 86 | 'meanDelay' => $airport['totalDelay'] / ($airport['numFlights'] - $airport['numCancellations']), |
||
| 87 | 'cancellationRate' => $airport['numCancellations'] / $airport['numFlights'] |
||
| 88 | ]; |
||
| 89 | } |
||
| 90 | } |
||
| 91 |