drgomesp / trip-sorter

:trolleybus: Sorting trip boarding cards like there is no tomorrow!

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

TripSorter

Table of Contents

  1. Introduction
  2. Installation
  3. Running Specifications
  4. Architecture
  5. Destinations
  6. Boarding Cards
  7. Trip Sorter

Introduction

Installation

To install the TripSorter, simply run the composer install command from the root directory of the project (make sure you have Composer installed):

php composer.phar install --prefer-dist

Running Specifications

To run the phpspec specifications, simply execute the following command from the root directory of the project:

bin/phpspec run

Architecture

Destinations

The basic interface of destinations is the following:

interface DestinationInterface
{
    /**
     * Prints the destination in a human-readable form.
     *
     * @return string
     */
    public function __toString();
}

Boarding Cards

The basic interface of boarding cards is the following:

interface BoardingCardInterface
{
    /**
     * @return \TripSorter\Destination\DestinationInterface
     */
    public function getFrom();

    /**
     * @return \TripSorter\Destination\DestinationInterface
     */
    public function getTo();
}

The architecture is also composed by special types of boarding cards:

  • BusBoardingCardInterface
  • FlightBoardingCardInterface
  • TrainBoardingCardInterface

Trip Sorter

The class responsible for sorting an array of boarding cards is the TripSorter:

class TripSorter
{
    public function sort(array $boardingCards)
    {
        $sorted = [array_pop($boardingCards)];

        while (count($boardingCards) > 0) {
            foreach ($boardingCards as $key => $card) {
                if ( ! $card instanceof BoardingCardInterface) {
                    unset($boardingCards[$key]);
                    continue;
                }

                if (end($sorted)->getTo()->__toString() === $card->getFrom()->__toString()) {
                    array_push($sorted, $card);
                } elseif (reset($sorted)->getFrom()->__toString() === $card->getTo()->__toString()) {
                    array_unshift($sorted, $card);
                }

                unset($boardingCards[$key]);
            }
        }

        return $sorted;
    }
}

by Daniel Ribeiro.

About

:trolleybus: Sorting trip boarding cards like there is no tomorrow!


Languages

Language:PHP 100.0%