Set condition based on inner text of node? - javascript

(function() {
var i=0;
var f=function() {
let l=document.querySelector("*[data-control-name=withdraw_single]");
if (!!l) {
setTimeout(function() {
l.click();
}, 100);
setTimeout(function() {
document.querySelector(".artdeco-modal .artdeco-button--primary").click();
},1500);
setTimeout(function() {
f();
},2500);
}
};
f();
})()
The above javascript bookmarklet works well for automating the invitation withdraw process on LinkedIn. However, there is a value in this element that I am hoping to factor in:
<time class="time-badge time-ago">
1 day ago
</time>
Any idea on how to add a condition to only move forward with the process ONLY if this 'time-ago' value is greater than [X] days ago, otherwise STOP the process just provide an alert like 'All invites older than [X] days ago withdrawn.'

Ciao, you could try to do this:
...
let val = parseInt(document.querySelector(".time-badge").innerText.split(' ')[0]);
if (val > [X]){
// go forward
}
else {
// stop
alert('All invites older than [X] days ago withdrawn.');
}

var str = "<time class=\"time-badge time-ago\"> 1 day ago </time>";
var patt = /\> (.*?) day ago \<\/time>/i;
var result = str.match(patt);
if(result !== undefined && result !== null){
var day = parseInt(result[1]);
if(day <= 10){
// include results upto 10 days
} else {
// exclude results
}
}

Related

Determining time remaining until bus departs

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");

Five Consecutive days excluding weekends

I have written a code that raises a flag when number of leaves taken by a person exceeds 5 business days. However, it doesn't raise the flag when we have weekend in middle. Say, someone takes leave on 23,24 and then on 27,28 and 29. As 25 and 26 are weekends, tool doesn't count it. Can someone help me on how i must check the weekend dates here and push the value as "Yes" that includes weekend dates ?
function PrepareReport(reportData) {
var vacationData = [];
var dayValuesStr = '';
var dayValuesArray = [];
if ($("#ddlfromYear").val() == $("#ddltoYear").val()) {
count = parseInt($("#ddltoMonth").val()) - parseInt($("#ddlfromMonth").val());
}
else {
count = 12 - parseInt($("#ddlfromMonth").val()) + parseInt($("#ddltoMonth").val());
}
//val.ResourceID FullName EnterpriseID WorkOrder Domain Totalhours
vacationData.push(reportData.FullName);
vacationData.push(reportData.EnterpriseID);
vacationData.push(reportData.WorkOrder);
vacationData.push(reportData.Domain);
if (reportData.IsOffshore == 1) {
vacationData.push('Offshore');
}
else {
vacationData.push('Onshore');
}
vacationData.push(reportData.TOTALHOURS);
var counter = 0;
FlagCounterLastVal = 0;
vacationData.push("No");
for (var monthNum = 0; monthNum <= count; monthNum++) {
dayValuesStr = reportData['MONTH' + monthNum];
if (dayValuesStr) {
dayValuesArray = dayValuesStr.split(',');
var countArray = dayValuesArray.length - 1;
$.each(dayValuesArray, function (key, val) {
if (val.endsWith('.00'))//round off values
{
if (parseInt(val) == 0) {
vacationData.push('-');
counter = 0; // resetting counter to 0 for non-consecutive days
}
else {
if (FlagCounterLastVal > 0) {
counter = FlagCounterLastVal;
}
counter++;
vacationData.push(parseInt(val));
****if (counter >= 5 && FlagCounterLastVal == 0) {
var index = vacationData.indexOf("No");
vacationData[index] = "Yes";
}****
if (key == (countArray) && count > 0) { // vacation taken at the month ends
FlagCounterLastVal = counter;
}
}
}
else {
vacationData.push(val);
}
});
}
}
return vacationData;
}
You can use getDay for that.
var day = yourDateObject.getDay();
var isWeekend = (day === 6) || (day === 0);
6 = Saturday, 0 = Sunday
I won't be sharing code here as it's Data Structure and would like you to think a little bit, and try yourself first. If still you won't be able to code it then I will help you out in your code.
What I would do is have 2 arrays, both will be sorted this will help in search.
1. Having all weekends dates. // weekendArr
2. Leave dates taken by employee. //leaveArr
Steps
1. delete all the weekendArr dates from leaveArr.
2. Check if leaveArr have continues dates more then 5 or what ever you want it to be.
3. If it is greater then 5 then raise a flag for that employee.
Now you need to decide what data structure you will use to maintain employee leaves, employeeID, and leave flag.
Hope this will be enough to figure out code now.

How to compare two dates with momentJS ignoring the year value?

Let's say a term starts from 1 November 2015 to 3 January 2016. The sample dates to compare are as follows ('YYYY-MM-DD'):
2015-10-12 = false
2015-11-01 = true (inclusive)
2015-12-20 = true
2015-01-03 = true (inclusive)
2016-01-30 = false
2017-11-21 = true (year is ignored)
2010-12-20 = true (year is ignored)
Is there a way that I can achieve this result with MomentJS?
It's possible using isBetween, but kind of messy.
function isWithinTerm(dateString) {
var dateFormat = '____-MM-DD', // Ignore year, defaults to current year
begin = '2015-10-31', // Subtract one day from start of term
end = '2016-01-04', // Add one day to finish of term
mom = moment(dateString, dateFormat); // Store to avoid re-compute below
return mom.isBetween(begin, end) || mom.add(1, 'y').isBetween(begin, end);
}
The reason I'm adding a year as an optional check is just for the January case since January of 2015 is obviously not between November 2015 and January 2016. I know it's kind of hacky, but I couldn't think of any simpler way of doing it.
It would work like this: https://jsfiddle.net/3xxe3Lg0/
var moments = [
'2015-10-12',
'2015-11-01',
'2015-12-20',
'2015-01-03',
'2016-01-30',
'2017-11-21',
'2010-12-20'];
var boundaries = [moment('2015-11-01').subtract(1, 'days'),moment('2016-01-03').add(1, 'days')];
for (var i in moments){
res = moments[i] + ': ';
if (
moment(moments[i]).year(boundaries[0].year()).isBetween(boundaries[0], boundaries[1]) ||
moment(moments[i]).year(boundaries[1].year()).isBetween(boundaries[0], boundaries[1])
){
res += 'true';
}
else{
res += 'false';
}
$('<div/>').text(res).appendTo($('body'));
}
EDIT: with a tiny change it would even work, if the upper boundary was not one but two (or more) years ahead from the lower one.
for (var i in moments){
res = moments[i] + ': ';
if (
moment(moments[i]).year(boundaries[0].year()).isBetween(boundaries[0], boundaries[1]) ||
moment(moments[i]).year(boundaries[0].year()+1).isBetween(boundaries[0], boundaries[1])
){
res += 'true';
}
else{
res += 'false';
}
$('<div/>').text(res).appendTo($('body'));
}

Trouble with returning value from function

Please, look at this code and tell me why doesn't work? i think that there is a problem with return in function. Thanks for all replays.
var movie1 = {
title: "Buckaroo Banzai",
genre: "Cult classic",
rating: 5,
showtimes: ["1:00pm", "3:00pm", "7:00pm"]
}
function getNextShowing(movie) {
var now = new Date().getTime();
for (var i = 0; i < movie.showtimes.length; i++) {
var showtime = getTimeFromString(movie.showtimes[i]);
if ((showtime - now) > 0) {
return "Next showing of " + movie.title + " is " + movie.showtimes[i];
}
}
return null;
}
function getTimeFromString(timeString) {
var theTime = new Date();
var time = timeString.match(/(\d+)(?::(\d\d))?\s*(p?)/);
theTime.setHours( parseInt(time[1]) + (time[3] ? 12 : 0) );
theTime.setMinutes( parseInt(time[2]) || 0 );
return theTime.getTime();
}
var nextShowing = getNextShowing(movie1);
alert(nextShowing);
The issue is with this line of code:
if ((showtime - now) > 0)
(showtime - now) is always less than zero therefore the getNextShowing() function always returns null;
I tested the above code, and it only returned me a null when the time in my computer is greater than or equal to 7:00pm.
Otherwise it works fine. Try changing the timing of the showtimes array, so that they are ahead of current time in your computer. Or try running it during the morning :).
I think that is all you need to do.

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