So, I have this web server that parses an XML-file with a certain 'time-period'.
The time-period is presented as follows (I can't change this):
00:05:00
00:09:15
01:13:15 in an HH:MM:SS format.
I want to do an _.filter() select on all objects with a date between for instance 00:00:00 and 00:10:00, and then a filter with all objects between 00:10:00 and 00:20:00.
EDIT (clarification): With the time periods are 'times watched'. Let's say there are 50 entries of the time period, ranging from 00:00:00 to 1:30:00, but I want to make a new list that contains
This means I need some way to say: 'Select all time periods between zero minutes and 10 minutes. Give me a list of those. Compute the mean'.
For that, I would need to have some possibility to do arithmetic operations, seeing I would like to
However, the Javascript Date object doesn't seem to handle 'just times' that well, neither does the moment.js library. How would I go for this?
Here is how I would do in JS:
times=['00:05:00', '00:09:15', '01:13:15'];
First get seconds
function getsec(time){
arr=time.split(':');
return (+arr[0])*3600 + (+arr[1])*60 + (+arr[2]);
}
times.map(getsec)
[ 300, 555, 4395 ]
Then filter times into slots of particular time period
function filter(last, curr, index, array){
chk=parseInt(curr/600); //slots for 10 minutes
if (typeof last[chk] === 'undefined')
{
last[chk]=[];
last[chk].push(curr);
}
else
last[chk].push(curr);
return(last)
}
times.map(getsec).reduce(filter,[]);
[ [ 300, 555 ], , , , , , , [ 4395 ] ]
Returns array of arrays. Each child array contains times within slots in increasing order
Calculate mean
function avg(last, curr, index, array){
if(index==array.length-1)
return (last+curr)/array.length;
else
return last+curr;
}
times.map(getsec).reduce(avg,0);
1750
function getavg(arr){
return arr.reduce(avg,0);
}
times.map(getsec).reduce(filter,[]).map(getavg);
[ 427.5, , , , , , , 4395 ]
Since we are dealing with array of arrays we need a wrapper.
Finally I would say that if you have many entries, databases would be faster.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With