Skip to content

Instantly share code, notes, and snippets.

@devmsh
Last active June 18, 2017 12:39
Show Gist options
  • Save devmsh/24442696068740f7544b39fc4058aa27 to your computer and use it in GitHub Desktop.
Save devmsh/24442696068740f7544b39fc4058aa27 to your computer and use it in GitHub Desktop.
FreeAt challenge solution using Intervals
<?php
use \Achse\Math\Interval\Utils\StringParser\IntegerIntervalStringParser as Parser;
require_once 'vendor/autoload.php';
const FREE_TIME = "01:00:00";
$user = [
"workHours" => [
["from" => "08:00:00", "to" => "16:00:00"],
[],
["from" => "08:00:00", "to" => "16:00:00"],
[],
["from" => "08:00:00", "to" => "16:00:00"],
[],
["from" => "08:00:00", "to" => "16:00:00"],
],
"sessions" => [
[
"date" => "6/17/2017", "status" => "approved",
"from" => "09:00:00", "to" => "11:00:00",
],
[
"date" => "6/17/2017", "status" => "approved",
"from" => "16:00:00", "to" => "18:00:00",
],
[
"date" => "6/17/2017", "status" => "new",
"from" => "12:00:00", "to" => "14:00:00",
],
],
];
/**
* Convert a from and to time strings to integer intervals
* and add extra time before and after the interval if needed
* @param $workingHours
* @param string $extra
* @return \Achse\Math\Interval\Intervals\IntegerInterval
*/
function toInterval($workingHours, $extra = "00:00:00")
{
$from = timeToNumber(isset($workingHours['from']) ? $workingHours['from'] : 0) - timeToNumber($extra);
$to = timeToNumber(isset($workingHours['to']) ? $workingHours['to'] : 0) + timeToNumber($extra);
return Parser::parse("($from, $to)");
}
/**
* Convert the time string to integer
* e.g. 11:30 will be converted to 11.5 then 1150
* @param $time
* @return integer
*/
function timeToNumber($time)
{
return (date('H', strtotime($time)) + date('i', strtotime($time)) / 60) * 100;
}
function freeAt($user, $newSession)
{
$weekDay = date('l', strtotime($newSession['date']));
$week = ["Saturday", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday"];
$workingHours = $user['workHours'][array_search($weekDay, $week)];
$newSessionInterval = toInterval($newSession);
if (toInterval($workingHours)->isContaining($newSessionInterval)) {
return !(collect($user['sessions'])
->where('date', $newSession['date'])
->where('status', "approved")
->first(function ($approvedSession) use ($newSessionInterval) {
return $newSessionInterval->getIntersection(toInterval($approvedSession, FREE_TIME));
}));
}
return false;
}
$isFree = freeAt($user, ["date" => "6/17/2017", "from" => "11:00:00", "to" => "15:00:00"]);
var_dump($isFree);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment