Related
I have an array of stringified dates like,
arr = ["9-7-2020", "11-7-2020", "12-7-2020", "10-7-2020", "16-7-2020", "15-7-2020", "19-7-2020"]
now I want to check if this array consist of atleast 3 consecutive dates, so what should be the best possible way to do it in node?
One approach could be this, where we get and sort the timestamps of each date, and then we can check for consecutive dates by subtracting a day's milliseconds multiplied by its index and checking if the same timestamp occurs more than or equal to N times.
const arr = ["9-7-2020", "11-7-2020", "12-7-2020", "10-7-2020", "16-7-2020", "15-7-2020", "19-7-2020"];
const ONE_DAYS_MILLIS = 1000 * 60 * 60 * 24;
const hasNConsecutive = (dates, N) => {
// Remove duplicate dates if any
const uniqueDays = [... new Set(dates)];
const dateOccurrences = uniqueDays
.map((date) => date.split('-'))
// Get a timestamp for each date
.map(([day, month, year]) => new Date(year, month, day).getTime())
.sort()
// Since we have sorted the timestamps we can now check for
// consecutive dates by subtracting a day multiplied
// by the index and checking if the same timestamp
// occurs more than or equal to N times
.map((ts, index) => ts - index * ONE_DAYS_MILLIS)
.reduce((count, ts) => {
count[ts] = (count[ts] || 0) + 1;
return count;
},
{});
return Object.values(dateOccurrences).some((times) => times >= N);
};
const result = hasNConsecutive(arr, 3);
console.log(result);
Or if you are using lodash you can do the same thing a little bit easier.
const arr = ["9-7-2020", "11-7-2020", "12-7-2020", "10-7-2020", "16-7-2020", "15-7-2020", "19-7-2020"];
const ONE_DAYS_MILLIS = 1000 * 60 * 60 * 24;
const result = _
.chain(arr)
.uniq()
.map((date) => date.split('-'))
.map(([day, month, year]) => new Date(year, month, day).getTime())
.sort()
.map((ts, index) => ts - index * ONE_DAYS_MILLIS)
.countBy(_.identity)
.values()
.some((count) => count >= 3)
.value();
console.log(result);
<script src="https://cdn.jsdelivr.net/npm/lodash#4.17.19/lodash.min.js"></script>
You could crate Date objects from those date string, sort them and then go through the array and check if the previous date plus one day is equal to the current date and keep a count of how many times that condition is true in a row.
Here is an example:
const arr = ["9-7-2020", "11-7-2020", "12-7-2020", "10-7-2020", "16-7-2020", "15-7-2020", "19-7-2020"]
const requiredConsecutiveCount = 3;
const getDate = (dateStr) => new Date(dateStr.split("-").reverse().map(v => parseInt(v)).map((v, i) => i === 1 ? (v + 1) : v));
const hasConsecutive = arr.map(getDate)
.sort((a, b) => a.getTime() - b.getTime())
.some(function(v, i, arr) {
if (i > 0) {
const tmp = new Date(arr[i - 1]);
tmp.setDate(tmp.getDate() + 1);
if (tmp.getTime() === v.getTime()) {
this.consecutiveCount++;
} else {
this.consecutiveCount = 0;
}
}
return this.consecutiveCount === requiredConsecutiveCount;
}, {
consecutiveCount: 0
});
console.log(hasConsecutive);
Probably my way of converting from a string date to a Date object is more complex than it has to be.
Two things needed here:
Sort the array by date, probably need to convert dates along the way
Then check if date diff to next element is 1 day and date diff to the element after that is 2 days
var arr = ["9-7-2020", "11-7-2020", "12-7-2020", "10-7-2020", "16-7-2020", "15-7-2020", "19-7-2020"]
var ONE_DAY = 24 * 60 * 60 * 1000;
function hasNConsecutive(arr, numConsecutive){
// new Date() is locale dependent. You might need to modify this heavily if you need to be locale-agnostic
var dateArray = arr.map(function(d){return new Date(d).getTime()}).sort();
var consecutiveCount = 1;
for(var i=1; i<dateArray.length; i++) {
if(dateArray[i] - dateArray[i-1] != ONE_DAY) {
consecutiveCount = 1;
continue;
}
consecutiveCount++;
if(consecutiveCount == numConsecutive) return true;
}
return false;
}
console.log(hasNConsecutive(arr, 3));
what's happening here is, we are making the month or the day a two digit if it isn't one, then we are constructing integer which has value like this "YYYYMMDD" then we are subtracting from three times of the first day with sum of three consecutive days, answer will be three if they are consecutive days
(caution: no duplicate dates must exist)
var arr = ["9-7-2020", "11-7-2020", "12-7-2020", "10-7-2020", "16-7-2020", "15-7-2020", "19-7-2020"]
arr.map((v) => (v.split("-").map((val) => (val.length == 1 ? "0" + val : val)).reverse().join(""))).map((value) => (parseInt(value))).sort((a, b) => (a > b ? 1 : a < b ? -1 : 0)).forEach((v, i, arr2) => {
if (i + 2 < arr2.length) {
var three = (v + arr2[i + 1] + arr2[i + 2]) - (v * 3)
if (three == 3) console.log('three consecutive days')
}
})
I have an array of dates:
const dates = ['date1', 'date2', 'date3', 'date4', 'date5'];
and a function that gets two values and returns true if two dates are in same week
function isSameWeek(a,b){
// some code
return true or false;
}
I want to filter the dates array in a way that none of it's values are in same week(one for each week).
For example if isSameWeek('date1', 'date2')=true , the filtered Array should be filtered=['date1', 'date3', 'date4', 'date5']
Helps are appreciated :)
If the dates are sorted, this can be accomplished with a single pass:
// monkey patching here for example sake (ignore this)
Date.prototype.getWeekNumber = function() {
var d = new Date(Date.UTC(this.getFullYear(), this.getMonth(), this.getDate()));
var dayNum = d.getUTCDay() || 7;
d.setUTCDate(d.getUTCDate() + 4 - dayNum);
var yearStart = new Date(Date.UTC(d.getUTCFullYear(),0,1));
return Math.ceil((((d - yearStart) / 86400000) + 1)/7);
}
const isSameWeek = (a, b) => a.getWeekNumber() == b.getWeekNumber();
function getWeeklyDates(dates)
{
// can remove the sort() if already sorted
dates.sort((a, b) => a - b)
// filter out in a single pass
return dates.filter((date, index) => {
return index > 0 ? !isSameWeek(date, dates[index - 1]) : true; // not in the same week
});
}
const dates = [
new Date('2020-01-01'),
new Date('2020-02-01'),
new Date('2020-01-03'),
new Date('2020-03-05'),
new Date('2020-03-03')
];
console.log(getWeeklyDates(dates));
You should check out Array's reduce method:
return dates.reduce((unique, date) => {
if (unique.some(it => isSameWeek(it, date)) return unique;
return [...unique, date];
}, [])
I have an array of time duration strings as below, and would like to find the minimum time.
group = ["41:04", "54:50", "01:03:50"] // note this is mix of **mm:ss** and **HH:mm:ss**
I am using moment:
group.map(tid => moment.duration(tid,'hh:mm:ss').asSeconds());
but it interprets the first two elements as "hh:mm" instead of "mm:ss", and results in:
[147840, 197400, 3830]
However, the first element "41:04" is the shortest time duration.
Is there any way to get this right using moment? Or what is the best way to find the minimum time duration?
Note that if i concatenate zeros to the string by myself (ie, 00:41:04), it will be correct.
You could calculate the seconds elapsed using simple mathematics without using any libraries.
For example;
41:04 = 41 * 60 + 04
01:03:50 = 01 * (60 ^ 2) + 03 * 60 + 50
Creating simple function to calculate seconds elapsed.
const getSeconds = str => {
const sp = str.split(":");
let sum = 0;
sp.map((d, k) => {
sum += Number(d) * 60 ** (sp.length - 1 - k);
});
return sum;
};
Now you could loop through your array to get the seconds.
const min = group.reduce((d, k) => {
const a = getSeconds(d),
b = getSeconds(k);
return a < b ? d : k;
});
As a whole you could check out the code snippet below;
const group = ["50:04","41:04", "54:50", "01:03:50"];
const getSeconds = str => {
const sp = str.split(":");
let sum = 0;
sp.map((d, k) => {
sum += Number(d) * 60 ** (sp.length - 1 - k);
});
return sum;
};
const min = group.reduce((d, k) => {
const a = getSeconds(d),
b = getSeconds(k);
return a < b ? d : k;
});
console.log(min);
There might be more elegant solutions. But this is what I came up with. :D
I have this function:
function getInfoSchoolTime() {
var date = new Date();
var schoolBellTime = ["8:10","9:02","9:54","9:59","10:51","11:43","11:58","12:48","13:35","13:40","14:10","15:02","15:54"];
var remainingTime, currentHour;
for (var i = 0; i < schoolBellTime.length-1; i++) {
var startTime = schoolBellTime[i].split(":");
var endTime = schoolBellTime[i+1].split(":");
if (parseInt(startTime[0]) >= date.getHours() && parseInt(startTime[1]) >= date.getMinutes())
if (parseInt(endTime[0]) <= date.getHours() && parseInt(endTime[1]) <= date.getMinutes()) {
currentHour = i;
remainingTime=(parseInt(endTime[1])-date.getMinutes()+60)%60;
break;
}
}
if (currentHour == undefined)
return {current: -1, remaining: "not available"};
return {current: currentHour, remaining: remainingTime};
}
var info = getInfoSchoolTime();
console.log(info.current, info.remaining);
I have the schoolBellTime array that contains the timestamps of my school bell (I know, my school has strange bell times, these timestamps includes playtimes and lunchtime), this function is meant to return the 1st hour/2nd hour/3rd hour ... and the minutes that remains to the next hour/breaktime.
I checked all the code and can't find the error, it keeps returning {current: -1, remaining: "not available"}
The function at the top: setDateTime() takes a date and a time, and constructs a date object for that time.
Then I updated your function, I convert start and end to times on the current day, and then check if date.getTime() occurs between them. Then I simply subtract date.getTime() from end, and convert the result to minutes from milliseconds.
var setDateTime = function(date, str) {
var sp = str.split(':');
date.setHours(parseInt(sp[0], 10));
date.setMinutes(parseInt(sp[1], 10));
return date;
}
function getInfoSchoolTime() {
var date = new Date();
var schoolBellTime = ["8:10", "9:02", "9:54", "9:59", "10:51", "11:43", "11:58", "12:48", "13:35", "13:40", "14:10", "14:10", "15:02", "15:54"];
var remainingTime, currentHour, currentPeriod;
for (var i = 0; i < schoolBellTime.length - 1; i++) {
start = setDateTime(new Date(), schoolBellTime[i])
end = setDateTime(new Date(), schoolBellTime[i + 1])
if (date.getTime() > start.getTime() && date.getTime() < end.getTime()) {
currentHour = i
remainingTime = end.getTime() - date.getTime()
currentPeriod = ([schoolBellTime[i], schoolBellTime[i+1]]).join('-')
}
}
return {current: currentHour, currentPeriod: currentPeriod, remaining: Math.round(remainingTime * 0.0000166667)}
}
console.log(getInfoSchoolTime())
Here's a somewhat different approach, both to the code and the API. It uses two helper functions. Each should be obvious with a single example: pad(7) //=> "07" and pairs(['foo', 'bar', 'baz', 'qux']) //=> [['foo', 'bar'], ['bar', 'baz'], ['baz', 'qux']].
The main function takes a list of bell times and returns a function which itself accepts a date object and returns the sort of output you're looking for (period, remaining time in period.) This API makes it much easier to test.
const pad = nbr => ('00' + nbr).slice(-2)
const pairs = vals => vals.reduce((res, val, idx) => idx < 1 ? res : res.concat([[vals[idx - 1], val]]), [])
const schoolPeriods = (schoolBellTime) => {
const subtractTimes = (t1, t2) => 60 * t1.hour + t1.minute - (60 * t2.hour + t2.minute)
const periods = pairs(schoolBellTime.map(time => ({hour: time.split(':')[0], minute: +time.split(':')[1]})))
return date => {
const current = {hour: date.getHours(), minute: date.getMinutes()}
if (subtractTimes(current, periods[0][0]) < 0) {
return {message: 'before school day'}
}
if (subtractTimes(current, periods[periods.length - 1][1]) > 0) {
return {message: 'after school day'}
}
const idx = periods.findIndex(period => subtractTimes(current, period[0]) >= 0 && subtractTimes(period[1], current) > 0)
const period = periods[idx]
return {
current: idx + 1,
currentPeriod: `${period[0].hour}:${pad(period[0].minute)} - ${period[1].hour}:${pad(period[1].minute)}`,
remaining: subtractTimes(period[1], current)
}
}
}
const getPeriod = schoolPeriods(["8:10","9:02","9:54","9:59","10:51","11:43","11:58","12:48","13:35","13:40","14:10","14:10","15:02","15:54"])
console.log("Using current time")
console.log(getPeriod(new Date()))
console.log("Using a fixed time")
console.log(getPeriod(new Date(2017, 11, 22, 14, 27))) // will Christmas break ever come?!
I made a random guess at the behavior you would want if the date is outside the period range.
Internally, it creates a list of period objects that look like
[{hour:9, minute: 59}, {hour: 10, minute: 51}]
Perhaps it would be cleaner if instead of a two-element array it was an object with start and end properties. That would be an easy change.
Do note that for this to make sense, the bells need to be listed in order. We could fix this with a sort call, but I don't see a good reason to do so.
Here is an ES6 example using deconstruct (const [a,b]=[1,2]), array map, array reduce, partial application (closure) and fat arrow function syntax.
This may not work in older browsers.
//pass date and bellTimes to function so you can test it more easily
// you can partially apply bellTimes
const getInfoSchoolTime = bellTimes => {
//convert hour and minute to a number
const convertedBellTimes = bellTimes
.map(bellTime=>bellTime.split(":"))//split hour and minute
.map(([hour,minute])=>[new Number(hour),new Number(minute)])//convert to number
.map(([hour,minute])=>(hour*60)+minute)//create single number (hour*60)+minutes
.reduce(//zip with next
(ret,item,index,all)=>
(index!==all.length-1)//do not do last one, create [1,2][2,3][3,4]...
? ret.concat([[item,all[index+1]]])
: ret,
[]
);
return date =>{
//convert passed in date to a number (hour*60)+minutes
const passedInTime = (date.getHours()*60)+date.getMinutes();
return convertedBellTimes.reduce(
([ret,goOn],[low,high],index,all)=>
//if goOn is true and passedInTime between current and next bell item
(goOn && passedInTime<high && passedInTime>=low)
? [//found the item, return object and set goOn to false
{
current: index+1,
currentPeriod: bellTimes[index]+"-"+bellTimes[index+1],
remaining: high-passedInTime
},
false//set goOn to false, do not continue checking
]
: [ret,goOn],//continue looking or continue skipping (if goOn is false)
[
{current: 0, currentPeriod: "School is out", remaining: 0},//default value
true//initial value for goOn
]
)[0];//reduced to multiple values (value, go on) only need value
}
};
//some tests
const date = new Date();
//partially apply with some bell times
const schoolTime = getInfoSchoolTime(
[
"8:10", "9:02", "9:54", "9:59", "10:51",
"11:43", "11:58", "12:48", "13:35", "13:40",
"14:10", "14:10", "15:02", "15:54"
]
);
//helper to log time from a date
const formatTime = date =>
("0"+date.getHours()).slice(-2)+":"+("0"+date.getMinutes()).slice(-2);
date.setHours(11);
date.setMinutes(1);
console.log(formatTime(date),schoolTime(date));//11:01
date.setHours(15);
date.setMinutes(53);
console.log(formatTime(date),schoolTime(date));//15:53
date.setHours(23);
date.setMinutes(1);
console.log(formatTime(date),schoolTime(date));//23:01
I have e.g. an array with 2 objects (myObject1 and myObject2 like ).
Now when I add an third object I will check if time range overlaps.
Actually I don't know how I can do this in a performant way.
var myObjectArray = [];
var myObject1 = {};
myObject1.startTime = '08:00';
myObject1.endTime = '12:30';
...
var myObject2 = {};
myObject2.startTime = '11:20';
myObject2.endTime = '18:30';
...
myObjectArray.push(myObject1);
myObjectArray.push(myObject2);
Let assume we have some intervals
const INTERVALS = [
['14:00', '15:00'],
['08:00', '12:30'],
['12:35', '12:36'],
['13:35', '13:50'],
];
If we want to add new interval to this list we should check if new interval is not overlapping with some of them.
You can loop trough intervals and check if the new one is overlapping with others. Note that when comparing intervals you do not need Date object if you are sure it is the same day as you can convert time to number:
function convertTimeToNumber(time) {
const hours = Number(time.split(':')[0]);
const minutes = Number(time.split(':')[1]) / 60;
return hours + minutes;
}
There are two cases where intervals are NOT overlapping:
Before (a < c && a < d) && (b < c && b <d):
a b
|----------|
c d
|----------|
After where (a > c && a > d) && (b > c && b > d):
a b
|----------|
c d
|----------|
Because always c < d, it is enough to say that condition for NOT overlapping intervals is (a < c && b < c) || (a > d && b > d) and because always a < b, it is enough to say that this condition is equivalent to:
b < c || a > d
Negation of this condition should give us a condition for overlapping intervals. Base on De Morgan's laws it is:
b >= c && a <= d
Note that in both cases, intervals can not "touch" each other which means 5:00-8:00 and 8:00-9:00 will overlap. If you want to allow it the condition should be:
b > c && a < d
There are at least 5 situation of overlapping intervals to consider:
a b
|----------|
c d
|----------|
a b
|----------|
c d
|----------|
a b
|----------|
c d
|--------------------|
a b
|--------------------|
c d
|----------|
a b
|----------|
c d
|----------|
Full code with extra add and sort intervals functions is below:
const INTERVALS = [
['14:00', '15:00'],
['08:00', '12:30'],
['12:35', '12:36'],
['13:35', '13:50'],
];
function convertTimeToNumber(time) {
const hours = Number(time.split(':')[0]);
const minutes = Number(time.split(':')[1]) / 60;
return hours + minutes;
}
// assuming current intervals do not overlap
function sortIntervals(intervals) {
return intervals.sort((intA, intB) => {
const startA = convertTimeToNumber(intA[0]);
const endA = convertTimeToNumber(intA[1]);
const startB = convertTimeToNumber(intB[0]);
const endB = convertTimeToNumber(intB[1]);
if (startA > endB) {
return 1
}
if (startB > endA) {
return -1
}
return 0;
})
}
function isOverlapping(intervals, newInterval) {
const a = convertTimeToNumber(newInterval[0]);
const b = convertTimeToNumber(newInterval[1]);
for (const interval of intervals) {
const c = convertTimeToNumber(interval[0]);
const d = convertTimeToNumber(interval[1]);
if (a < d && b > c) {
console.log('This one overlap: ', newInterval);
console.log('with interval: ', interval);
console.log('----');
return true;
}
}
return false;
}
function isGoodInterval(interval) {
let good = false;
if (interval.length === 2) {
// If you want you can also do extra check if this is the same day
const start = convertTimeToNumber(interval[0]);
const end = convertTimeToNumber(interval[1]);
if (start < end) {
good = true;
}
}
return good;
}
function addInterval(interval) {
if (!isGoodInterval(interval)) {
console.log('This is not an interval');
return;
}
if (!isOverlapping(INTERVALS, interval)) {
INTERVALS.push(interval);
// you may also want to keep those intervals sorted
const sortedIntervals = sortIntervals(INTERVALS);
console.log('Sorted intervals', sortedIntervals);
}
}
// --------------------------------------
const goodIntervals = [
['05:31', '06:32'],
['16:00', '17:00'],
['12:31', '12:34']
];
let goodCount = 0;
for (const goodInterval of goodIntervals) {
if (!isOverlapping(INTERVALS, goodInterval)) {
goodCount += 1
}
}
console.log('Check good intervals: ', goodCount === goodIntervals.length);
// --------------------------------------
const ovelappingIntervals = [
['09:30', '12:40'],
['05:36', '08:50'],
['13:36', '13:37'],
['06:00', '20:00'],
['14:00', '15:00']
]
let badCount = 0;
for (const badInterval of ovelappingIntervals) {
if (isOverlapping(INTERVALS, badInterval)) {
badCount += 1
}
}
console.log('Check bad intervals: ', badCount === ovelappingIntervals.length);
// --------------------------------------
addInterval(goodIntervals[0])
You can try something like this:
var timeList = [];
function addTime() {
var startTime = document.getElementById("startTime").value;
var endTime = document.getElementById("endTime").value;
if (validate(startTime, endTime)){
timeList.push({
startTime: startTime,
endTime: endTime
});
print(timeList);
document.getElementById("error").innerHTML = "";
}
else
document.getElementById("error").innerHTML = "Please select valid time";
}
function validate(sTime, eTime) {
if (+getDate(sTime) < +getDate(eTime)) {
var len = timeList.length;
return len>0?(+getDate(timeList[len - 1].endTime) < +getDate(sTime) ):true;
} else {
return false;
}
}
function getDate(time) {
var today = new Date();
var _t = time.split(":");
today.setHours(_t[0], _t[1], 0, 0);
return today;
}
function print(data){
document.getElementById("content").innerHTML = "<pre>" + JSON.stringify(data, 0, 4) + "</pre>";
}
<input type="text" id="startTime" />
<input type="text" id="endTime" />
<button onclick="addTime()">Add Time</button>
<p id="error"></p>
<div id="content"></div>
Use moment-js with moment-range (broken reference)
Tested example:
const range1 = moment.range(a, c);
const range2 = moment.range(b, d);
range1.overlaps(range2); // true
See more examples in https://github.com/rotaready/moment-range#overlaps
Note, for the above code to work maybe you first do:
<script src="moment.js"></script>
<script src="moment-range.js"></script>
window['moment-range'].extendMoment(moment);
HTML code
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.12.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-range/2.2.0/moment-range.min.js"></script>
JavaScript code
var range = moment.range(new Date(year, month, day, hours, minutes), new Date(year, month, day, hours, minutes));
var range2 = moment.range(new Date(year, month, day, hours, minutes), new Date(year, month, day, hours, minutes));
range.overlaps(range2); // true or flase
Pretty neat solution and momentjs comes with tons of date and time utilities.
Use JavaScript Date() object to store time and then compare them if ending time of object1 is greater than starting time of object2 then they are overlapping.
You can compare them using > operator.
date1.getTime() > date2.getTime()
Demonstration given here
Usage of Date object
To determine whether the time range overlaps other time ranges you can utilize both moment.js and moment-range libraries.
First install moment-js and moment-range
Given you have an INTERVALS array that contains example objects:
const INTERVALS = [
{ START: 0, END: 10 },
{ START: 12, END: 30 },
...
]
You can use a function below:
const validateIntervalOverlaps = () => {
if (INTERVAL_START && INTERVAL__END) {
const timeInterval = moment.range(moment(INTERVAL_START), moment(INTERVAL_ENDS))
const overlappingInterval = INTERVALS.find(intervalItem => {
const interval = moment.range(moment(intervalItem.START), moment(intervalItem.END))
return timeInterval.overlaps(interval)
})
return overlappingInterval
}
}
Next, you can do what you need to do with overlappingInterval :) F.e. determine if it exists or use it in any other way. Good luck!
Here's something that might work.
// check if time overlaps with existing times
for (var j = 0; j < times.length; j++) {
let existing_start_time = moment(this.parseDateTime(this.times[j].start_time)).format();
let existing_end_time = moment(this.parseDateTime(this.times[j].end_time)).format();
// check if start time is between start and end time of other times
if (moment(start_time).isBetween(existing_start_time, existing_end_time)) {
times[i].error = 'Time overlaps with another time';
return false;
}
// check if end time is between start and end time of other times
if (moment(end_time).isBetween(existing_start_time, existing_end_time)) {
times[i].error = 'Time overlaps with another time';
return false;
}
}
https://momentjs.com/
You can check if there is an overlap by trying to merge a time range to the existing time ranges, if the total count of time ranges decrease after merge, then there is an overlap.
I found following articles which might help on handle merging ranges
Merge arrays with overlapping values
merge-ranges