Determining time remaining until bus departs - javascript

For our digital signage system, I'd like to show how long until the next bus departs. I've built the array that holds all the times and successfully (maybe not elegantly or efficiently) gotten it to change all that to show how much time is remaining (positive or negative) until each listed departure.
I need a nudge in the right direction as to how to determine which bus is next based on the current time. If there is a bus in 7 minutes, I only need to display that one, not the next one that leaves in 20 minutes.
I was thinking perhaps a for loop that looks at the array of remaining times and stops the first time it gets to a positive value. I'm concerned that may cause issues that I'm not considering.
Any assistance would be greatly appreciated.
UPDATE: Unfortunately, all the solutions provided were throwing errors on our signage system. I suspect it is running some limited version of Javascript, but thats beyond me. However, the different solutions were extremely helpful just in getting me to think of another approach. I think I've finally come on one, as this seems to be working. I'm going to let it run over the holiday and check it on Monday. Thanks again!
var shuttleOrange = ["09:01", "09:37", "10:03", "10:29", "10:55", "11:21", "11:47", "12:13", "12:39", "13:05", "13:31", "13:57", "14:23", "14:49", "15:25", "15:51", "16:17", "16:57", "17:37", "18:17"];
var hFirst = shuttleOrange[0].slice(0,2);
var mFirst = shuttleOrange[0].slice(3,5);
var hLast = shuttleOrange[shuttleOrange.length-1].slice(0,2);
var mLast = shuttleOrange[shuttleOrange.length-1].slice(3,5);
var theTime = new Date();
var runFirst = new Date();
var runLast = new Date();
runFirst.setHours(hFirst,mFirst,0);
runLast.setHours(hLast,mLast,0);
if ((runFirst - theTime) >= (30*60*1000)) {
return "The first Orange Shuttle will depart PCN at " + shuttleOrange[0] + "."
} else if (theTime >= runLast) {
return "Orange Shuttle Service has ended for the day."
} else {
for(var i=0, l=shuttleOrange.length; i<l; i++)
{
var h = shuttleOrange[i].slice(0,2);
var m = shuttleOrange[i].slice(3,5);
var departPCN = new Date();
departPCN.setHours(h,m,0);
shuttleOrange[i] = departPCN;
}
for(var i=shuttleOrange.length-1; i--;)
{
//var theTime = new Date();
if (shuttleOrange[i] < theTime) shuttleOrange.splice(i,1)
}
var timeRem = Math.floor((shuttleOrange[0] - theTime)/1000/60);
if (timeRem >= 2) {
return "Departing in " + timeRem + " minutes."
} else if (timeRem > 0 && timeRem < 2) {
return "Departing in " + timeRem + " minute."
} else {
return "Departing now."
}
}

You only need to search once to find the index of the next scheduled time. Then as each time elapses, increment the index to get the next time. Once you're at the end of the array, start again.
A sample is below, most code is setup and helpers. It creates a dummy schedule for every two minutes from 5 minutes ago, then updates the message. Of course you can get a lot more sophisticated, e.g. show a warning when it's in the last few minutes, etc. But this shows the general idea.
window.addEventListener('DOMContentLoaded', function() {
// Return time formatted as HH:mm
function getHHmm(d) {
return `${('0'+d.getHours()).slice(-2)}:${('0'+d.getMinutes()).slice(-2)}`;
}
var sched = ["09:01", "09:37", "10:03", "10:29", "10:55", "11:21", "11:47",
"12:13", "12:39", "13:05", "13:31", "13:57", "14:23", "14:49",
"15:25", "15:51", "16:17", "16:57", "17:37", "18:17","21:09"];
var msg = '';
var msgEl = document.getElementById('alertInfo');
var time = getHHmm(new Date());
var index = 0;
// Set index to next scheduled time, stop if reach end of schedule
while (time.localeCompare(sched[index]) > 0 && index < sched.length) {
++index;
}
function showNextBus(){
var time = getHHmm(new Date());
var schedTime;
// If run out of times, next scheduled time must be the first one tomorrow
if (index == sched.length && time.localeCompare(sched[index - 1]) > 0) {
msg = `Current time: ${time} - Next bus: ${sched[0]} tomorrow`;
// Otherwise, show next scheduled time today
} else {
// Fix index if rolled over a day
index = index % sched.length;
schedTime = sched[index];
msg = `Current time: ${time} - Next bus: ${schedTime}`;
if (schedTime == time) msg += ' DEPARTING!!';
// Increment index if gone past this scheduled time
index += time.localeCompare(schedTime) > 0? 1 : 0;
}
msgEl.textContent = msg;
// Update message each second
// The could be smarter, using setInterval to schedule running at say 95%
// of the time to the next sched time, but never more than twice a second
setInterval(showNextBus, 1000);
}
showNextBus();
}, false);
<div id="alertInfo"></div>
Edit
You're right, I didn't allow for the case where the current time is after all the scheduled times on the first running. Fixed. I also changed all the string comparisons to use localeCompare, which I think is more robust. Hopefully the comments are sufficient.

I have used filter for all shuttle left after the right time and calculated how much time left for the first one.
var shuttleOrange = ["09:01", "09:37", "10:03", "10:29", "10:55", "11:21", "11:47", "12:13", "12:39", "13:05", "13:31", "13:57", "14:23", "14:49", "15:25", "15:51", "16:17", "16:57", "17:37", "18:17"];
var d = new Date();
var h = d.getHours();
var m = d.getMinutes();
var remainShuttle = shuttleOrange.filter(bus => bus.substring(0,2) > h || (bus.substring(0,2) == h && bus.substring(3,5) > m));
var leftMinutes = (parseInt(remainShuttle[0].substring(0,2))*60 + parseInt(remainShuttle[0].substring(3,5)) - (parseInt(h) *60 + parseInt(m)));
console.log(parseInt(leftMinutes / 60) + " hours and " + leftMinutes % 60 +" minutes left for next shuttle");

Related

How do I get daily step count in a gear fit 2 pro web based watchface?

I am building a html/js powered watchface for the gear fit 2 pro and I'm having trouble accomplishing what seems like a simple task: getting the daily step count.
I have poured over the documentation, but it only describes how to count either steps since the watchface has started, or steps since the device has been booted. Other watchfaces immediately detect the system-wide step count and display it, but I don't see how this is possible!
Does anyone have an example of how to do this? I suspect the stepdifference or readrecorderdata functions might be involved, but the first is impossible to use due to inadequate documentation and the second does not seem to actually be present in the device.
You can setAccumulativePedometerListener() for the time period sensor data required. In you case you can reset the listener at end of the day. I've written a pseudo_code for you to show daily step count.
var sensor_data = document.getElementById("sensor-data");
var step_count=0,
offset=0, // to reduce yesterday's data
currentDailyStep=0;
function updateTime() {
var datetime = tizen.time.getCurrentDateTime(),
hour = datetime.getHours(),
minute = datetime.getMinutes(),
second = datetime.getSeconds();
if(hour === 23 && minute === 59 && second === 59){ // at the end of the day
tizen.humanactivitymonitor.unsetAccumulativePedometerListener();
tizen.humanactivitymonitor.stop("PEDOMETER");
offset = step_count; // store today's count
pedometer_init(); //reset
}
/*
* Other Codes
* ............
* .........
*/
}
function onchangedCB(pedometerInfo) {
step_count = pedometerInfo.accumulativeTotalStepCount;
currentDailyStep = step_count - offset; // totl count - total count till yesterday
sensor_data.innerHTML = currentDailyStep;
}
function pedometer_init(){
tizen.humanactivitymonitor.start("PEDOMETER");
tizen.humanactivitymonitor.setAccumulativePedometerListener(onchangedCB);
}
function init(){
pedometer_init();
}
window.onload = init();
You need to reduce offset manually as stop() function don't reset the count. Store the daily step data If you are interested to show statistics.
In addition, In Tizen Developers API References there's a Code Sample using HumanActivityRecorder to record Step count daily, Please Check If it helps:
function onerror(error){
console.log(error.name + ": " + error.message);
}
function onread(data){
for (var idx = 0; idx < data.length; ++idx)
{
console.log("*** " + idx);
console.log('totalStepCount: ' + data[idx].totalStepCount);
}
}
var type = 'PEDOMETER';
var now = new Date();
var startTime = now.setDate(now.getDate() - 7);
var anchorTime = (new Date(2000, 1, 2, 6)).getTime();
var query ={
startTime: startTime / 1000,
anchorTime: anchorTime / 1000,
interval: 1440 /* 1 day */
};
try{
tizen.humanactivitymonitor.readRecorderData(type, query, onread, onerror);
}
catch (err){
console.log(err.name + ': ' + err.message);
}

JavaScript Array - all index over 0 are empty after loop

I have an array of date/timestamps saved as seconds, I'm looking to count the number of items that are between two timestamps (all times are assumed to be at midnight). I've cut down a larger function to the section that the problem seems to reside, let me know if you need any additional code.
var fullDay = 86399;
var end = parseInt(dataArray[0]) + parseInt(fullDay);
for (var i = 0; i < numberOfDays; i++) {
dataSegments[i] = sensorEventTotal(dataArray, end, previousEnd);
previousEnd = end;
end = parseInt(end) + parseInt(fullDay);
}
console.log(dataSegments.toString());
SensorEventTotal:
function sensorEventTotal (dataArray, end, previousEnd){
var counter = 0;
$.each(dataArray, function(i, item) {
if (parseInt(item) < end && parseInt(item) > previousEnd) {
counter++;
}
});
previousEnd = end;
return counter;
}
What I'm trying to do is to take the first date/time stamp and add 24 hours (fullDay value is 24 hours in seconds), I'm then looking to use that "end time" as the start point for the next loop with another 24 hours added onto that and so on.
In the end I'd want an array where each index stores the number of occurrences for each day e.g. dataSegments = [23,123,32,34] - so 23 events on day one, 123 events on day two etc.
At the moment this is the result I'm getting for dataSegments:
115,0,0,0,0,0
EDIT:
Sample of data in dataArray:
1496077569,1496077568,1496077567,1496077564,1496077563,1496077562,1496072956
Full array:
1496077569,1496077568,1496077567,1496077564,1496077563,1496077562,1496072956,1496072955,1496072951,1496072950,1496072949,1496072948,1496072809,1496072805,1496072804,1496072803,1495815090,1495815089,1495815088,1495807282,1495807281,1495807280,1495807279,1495807277,1495807276,1495807275,1495807274,1495807273,1495807267,1495807266,1495807265,1495805409,1495805408,1495805407,1495805406,1495805381,1495805380,1495805379,1495803061,1495803060,1495803059,1495803059,1495803000,1495802999,1495802998,1495786283,1495786282,1495786281,1495728263,1495728262,1495728261,1495728258,1495728257,1495728256,1495727698,1495727697,1495727696,1495727695,1495727694,1495727693,1495727491,1495727490,1495727489,1495727486,1495727485,1495727484,1495724286,1495724285,1495724284,1495724279,1495724278,1495724277,1495720363,1495720358,1495720357,1495720356,1495719373,1495719372,1495719368,1495719367,1495719366,1495717302,1495717301,1495717299,1495717298,1495717297,1495717296,1495713310,1495713309,1495713308,1495713305,1495713304,1495713303,1495713303,1495707902,1495707901,1495707897,1495707896,1495707895,1495707615,1495707611,1495707610,1495707609,1495707608,1495704627,1495704626,1495704625,1495704623,1495704622,1495704621,1495704133,1495704132,1495704128,1495704127,1495704126
This is what I managed to come up with. I hope code is clear just from variable names alone, given that the logic is very similar to yours.
const SECONDS_IN_DAY = 24 * 3600;
let events = [1496077569,1496077568,1496077567,1496077564,1496077563,1496077562,1496072956,1496072955,1496072951,1496072950,1496072949,1496072948,1496072809,1496072805,1496072804,1496072803,1495815090,1495815089,1495815088,1495807282,1495807281,1495807280,1495807279,1495807277,1495807276,1495807275,1495807274,1495807273,1495807267,1495807266,1495807265,1495805409,1495805408,1495805407,1495805406,1495805381,1495805380,1495805379,1495803061,1495803060,1495803059,1495803059,1495803000,1495802999,1495802998,1495786283,1495786282,1495786281,1495728263,1495728262,1495728261,1495728258,1495728257,1495728256,1495727698,1495727697,1495727696,1495727695,1495727694,1495727693,1495727491,1495727490,1495727489,1495727486,1495727485,1495727484,1495724286,1495724285,1495724284,1495724279,1495724278,1495724277,1495720363,1495720358,1495720357,1495720356,1495719373,1495719372,1495719368,1495719367,1495719366,1495717302,1495717301,1495717299,1495717298,1495717297,1495717296,1495713310,1495713309,1495713308,1495713305,1495713304,1495713303,1495713303,1495707902,1495707901,1495707897,1495707896,1495707895,1495707615,1495707611,1495707610,1495707609,1495707608,1495704627,1495704626,1495704625,1495704623,1495704622,1495704621,1495704133,1495704132,1495704128,1495704127,1495704126];
events = events.reverse();
let midnight = events[0] - events[0] % SECONDS_IN_DAY; // midnight before the first event
const eventsPerDay = []; // results array
const nrDays = 7; // lets count events for one week
let daysCounted = 0, eventsChecked = 0;
while (daysCounted < nrDays) {
midnight += SECONDS_IN_DAY;
let currentEvent = events[eventsChecked];
let eventsInThisDay = 0;
while (currentEvent < midnight) {
eventsInThisDay++;
eventsChecked++;
currentEvent = events[eventsChecked];
}
eventsPerDay[daysCounted] = eventsInThisDay;
daysCounted++;
}
console.log(eventsPerDay);
Notice that I reverse the sample array before running my execution. That is because your sample starts at May 29 and ends at May 25, so it's running backwards in time.
I encourage you to try your own code on a reversed array, might very well be the case that your solution is correct.
If you do not want to reverse the array, you could "reverse the counting" by going from the latest midnight to the first midnight, subtracting 1 day on each iteration.
In my opininion (and coming example), you can do it a bit simpler. Also, I've noticed a little problem in your function: if your dataArray and number of days (let's call them N) were big, you would have to iterate over the data array N number of times. It could become inefficient. Luckily you can do it in one loop iteration:
let sensorEventTotal = (data, start, daysNum) => {
// We create array of length daysNum filled with 0's.
let days = new Array(daysNum);
days.fill(0);
for(let entry of data) {
// If below the start timestamp, continue loop.
if(entry < start) continue;
// We calculate which day it is.
let index = parseInt((entry - start) / fullDay);
// We check if the entry is not from days we do not count.
if(index < daysNum)
days[index]++;
}
return days;
}
Code with working examples: http://jsbin.com/lekiboruki/edit?js,console.
EDIT: You didn't mention if your dataArray is sorted. My answer would also work on unsorted arrays.

setTimeout executes faster than simultaneous setInterval

So, I have a setInterval and a setTimeout running simultaneously in this click-o-meter thing I'm doing: the user enters an specified number of seconds he/she wants the game to run for, and then it counts how many clicks you have done, what was the average time between each click, and the average amount of clicks per second you've made during the specified period of time.
<html>
<head></head>
<body>
<input type='text' id='timerInput'></input>
<button id='btn'>Click</button>
<script>
var before;
var now;
var clicks = 0;
var cts = 0; //Stands for 'Clicks This Second'
var intervals = new Array();
var cps = new Array();
var cpsCounter;
var timer;
var canContinue = true;
var timerInput = document.getElementById('timerInput');
var timerTime;
var wasBad = false;
document.getElementById('btn').onclick = function() {
if(canContinue) {
if(clicks <= 0) {
if(timerInput.value.replace(/\D/, '') === timerInput.value) {
wasBad = false;
timerTime = parseInt(timerInput.value.replace(/\D/, '')) * 1000;
before = new Date();
cpsCounter = window.setInterval(ctsFunction, 1000);
timer = window.setTimeout(finish, timerTime);
}else{
alert('Only numbers please!');
wasBad = true;
}
}else{
now = new Date();
console.log(now - before);
intervals.push(now - before);
before = new Date();
}
if(!wasBad){
clicks++;
cts++;
}
}else{console.log('Game ended');}
};
function ctsFunction() {
console.log('Clicks this second: ' + cts);
cps.push(cts);
cts = 0;
}
function finish() {
console.log('Clicks: ' + clicks);
console.log('Average Speed (ms): ' + Math.floor(intervals.reduce(function(a, b){return a + b;}) / (clicks - 1)));
console.log('Average Speed (clicks per second): ' + (cps.reduce(function(a, b){return a + b;}) / cps.length));
intervals = new Array();
console.log('cps.length: ' + cps.length);
cps = new Array();
clicks = 0;
cts = 0;
window.clearInterval(cpsCounter);
canContinue = false;
}
</script>
</body>
</html>
So, the problem is that when the gmae finishes, that is, when timer reaches the end, ctsFunction() is supposed to run once more at the last second, so it can register data from it; but finish() is executed faster, or prior to ctsFunction(), thus clearing the cpsCounter interval and not allowing it to do anything on the last second. I've tried adding some extra milliseconds to timer, but if you choose to run the game for enough seconds, the same problem will eventually happen (e.g. if you add 1ms, the problem will be solved for up to 2 seconds, but not for more).
I have a setInterval and a setTimeout running simultaneously
It will never happens because javascript is a single thread language. There is no matter what is in your code, javascript can't execute two commands simultaneously.
And one more:
timer delay is not guaranteed. JavaScript in a browser executes on a
single thread asynchronous events (such as mouse clicks and timers)
are only run when there’s been an opening in the execution.
Read this article to understand how javascript timers work.

AngularJS Countdown within an ng-repeat

I have a small AngularJS app which searches and retrieves a listing of users and their next scheduled meeting (assuming one is scheduled in the next 8 hours) brought back from the server using JSON with the time format in UTC for ease of calculation to local times. Each user could have a different status (busy until x time, free until x time).
What I would like to accomplish is to be able to update the DOM with time remaining until the meeting scheduled has completed or time left until the meeting starts. I have some code working sort of, but because I am apparently not doing this correctly with only a few entries in the result set it brings the browser to a near standstill. Any suggestions would be appreciated!
My current code consists of the following snippets:
[Main Page]
<tr ng-repeat="item in pagedItems[currentPage-1] | orderBy:sortingOrder:reverse" ng-class="{success:item._freeBusy=='Free', error:item._freeBusy=='Busy'}">
<td>{{item._firstName}}</td>
<td>{{item._lastName}}</td>
<td>{{item._facilityName}}</td>
<td>{{item._extension}}</td>
<td>{{item._description}}</td>
<td><a ng-hide="!item._extension" ng-click="dial(item)">Dial</a></td>
<td><button class="btn btn-primary" ng-click="openDetails(item)">Details</button></td>
<td>{{item._freeBusy}} {{item._timeLeft}} {{calculateTime(item._freeBusyTime,$index)}}</td>
</tr>
[Controller]
$scope.timeUntil = function(s) {
function isoToObj(s) {
var b = s.split(/[-T+:]/i);
return new Date(Date.UTC(b[0], --b[1], b[2], b[3], b[4], b[5]));
}
// Utility to add leading zero
function z(n) {
return (n < 10 ? '0' : '') + n;
}
// Convert string to date object
var d = isoToObj(s);
var diff = d - new Date();
// Allow for previous times
var sign = diff < 0 ? '-' : '';
diff = Math.abs(diff);
// Get time components
var hours = diff / 3.6e6 | 0;
var mins = diff % 3.6e6 / 6e4 | 0;
var secs = Math.round(diff % 6e4 / 1e3);
// Return formatted string
return sign + z(hours) + ' Hours ' + z(mins) + ' Min' + ':' + z(secs);// + ':' + z(secs)
}
$scope.calculateTime = function(s, idx) {
timeoutID = $timeout(function() {
$scope.items[idx]._timeLeft = $scope.timeUntil(s);
$scope.calculateTime(s, idx);
}, 1000);
};
EDIT
I understand the issues as mentioned below, what I am struggling with is how to register this corretly. As it could be up to 15+ separate times updating to a single tick that's where I am getting lost.
You are registering way more timeouts than you think. Every time angular renders your view, you register new timeout handlers. Add a counter of your callback and watch the count go:
$scope.called = 0;
$scope.calculateTime = function(s, idx) {
timeoutID = $timeout(function() {
$scope.items[idx]._timeLeft = $scope.timeUntil(s);
$scope.calculateTime(s, idx);
console.log(++$scope.called);
}, 1000);
};
See this plunk where I reproduced the bug: http://plnkr.co/edit/qJ4zDl6gc5C7Edg0T0gB. Just run it and watch the counter.
Why do you want to update your _timeLeft in the rendering cycle? Why not do this:
$scope.called = 0;
setInterval(function() {
angular.forEach($scope.items, function function_name(item) {
item._timeLeft = $scope.timeUntil(item._freeBusyTime);
});
console.log(++$scope.called);
$scope.$apply();
}, 1000);
See new plunk: http://plnkr.co/edit/rVJ6p4VXDQvt7rjT6eka
You are calling $scope.calculateTime recursively! And you are modifying the list of items during the ng-repeat, which also causes and endless loop.
How about this: http://plnkr.co/edit/0JqK96irV4ETdWZYxO3P?p=preview
changed the html to refer to a separate array that doesn't affect ng-repeat:
<td>in {{_timeLeft[$index]}}</td>
which is updated as follows:
$scope._timeLeft = [];
var intervalID = window.setInterval(function() {
for (var i=0; i<$scope.items.length; i++) {
$scope._timeLeft[i] = $scope.timeUntil($scope.items[i]._freeBusyTime);
}
$scope.$apply();
}, 1000);
Note that $scope.$apply() is required to let Angular know that '_timeLeft' has been modified, which updates all references to it.
I do not think you should call $timeout every view update.
Instead, you can count down time within your controller and let view show the timer.
http://plnkr.co/edit/OUVdJyllzmVmPC0FhqYF?p=preview

Time validations (Javascript)

I have a form (Using JavaScript) in which users are supposed to enter information like their work start time, break start time, break end time and work end time. I have 4 textboxes for this purpose. Time entered into the textbox is in hhmm format (24-hour only).
Requirements:
1. The break times (start and end) must be within the work start and end time.
2. Break start must be before break end time.
3. Users can take up work shifts during the day or even overnight.
4. Work time(excluding breaks) should be less than 8 hours and greater than 4 hours.
So some typical valid entries would be:
User1-
Start time: 0900
Break start time:1300
Break end time:1400
End time:1600
User2-
Start time:2200
Break start time:2300
Break end time:2330
End time:0400
Some invalid entries would be:
Case1 - Break start before break end
Start time:2200
Break start time: 2330
Break end time: 2300
End time:0400
Case 2 -Breaks outside work time
Start time:2200
Break start time:1830
Break end time: 1900
End time:0400
I'm having trouble writing the validation code (JavaScript) for requirements 1,2 & 3. Please help me out.
Here's what I've got so far. (Please note: I cannot use DATE objects.)
var wrkSt = getElement('TB1').value;
var wrkSt_hr = parseFloat(wrkSt.substr(0,2));
var wrkSt_mn= parseFloat(wrkEd.substr(2,2));
var brkSt = getElement('TB2').value;
var brkSt_hr = parseFloat(brkSt.substr(0,2));
var brkSt_mn= parseFloat(brkEd.substr(2,2));
var brkEd = getElement('TB3').value;
var brkEd_hr = parseFloat(brkSt.substr(0,2));
var brkEd_mn= parseFloat(brkEd.substr(2,2));
var wrkEd = getElement('TB4').value;
var wrkEd_hr = parseFloat(wrkEd.substr(0,2));
var wrkEd_mn= parseFloat(wrkEd.substr(2,2));
var msg='';
if ((wrkSt_hr > wrkEd_hr) || ((wrkSt_hr == wrkEd_hr) && (wrkSt_mn >= wrkEd_mn)) )
{
msg+='shift overnight selected';
}
if (wrkEd_hr>12){wrkEd_hr-=12;}
if (wrkSt_hr >12){wrkSt_hr -=12;}
if (brkSt_hr>12){brkSt_hr-=12;}
if (brkEd_hr>12){brkEd_hr-=12;}
var Breakdiff = ((brkEd_hr - brkSt_hr)*60) + (brkEd_mn - brkSt_mn);
var Workdiff_tot = ((wrkEd_hr- wrkSt_hr)*60) + (wrkEd_mn -wrkSt_mn);
var Shiftdiff = Workdiff_tot - Breakdiff;
if (Shiftdiff > 480) //8hours = 8*60 = 480 min
{
msg+='Time greater than 8 hrs';
}
if (Shiftdiff < 240) //4 hours = 4*60 = 240 min
{
msg+='Time less than 4 hrs';
}
Please help me with the logic for checking breaks and work time. Thx for any help in advance!
function validate(start, breakStart, breakEnd, end) {
var minutes = [];
for (var i = 0; i < 4; ++i) {
var time = arguments[i];
if (!/^(?:[01]\d|2[0-3])[0-5]\d$/.test(time)) {
throw new Error("Invalid time " + time);
}
var minute = minutes[i] = time.substring(0, 2) * 60 + +time.substring(2);
if (i && minute < minutes[i - 1]) { // Take into account times that cross midnight.
minutes[i] = (minute += 24*60);
}
if (i && minute <= minutes[i - 1]) {
throw new Error("Out of order " + arguments[i - 1] + " and " + time);
}
}
if (minutes[3] - minutes[0] > 8*60) { throw new Error("Shift too long"); }
if (minutes[3] - minutes[0] > 4*60) { throw new Error("Shift too short"); }
}

Categories

Resources