Comparision between 2 Object - javascript

I am working on a course registration system.I need to check for time conflicts.
Already registered courses object:
{"00001":{"days":"Monday-Tuesday","hours":"11:40-12:30*13:40-15:30"}}
this means that 00001 course is in monday 11:40-12:30 in tuesday 13:40-15:30
Courses to register object:
{"00003":{"days":"Friday","hours":"9:40-10:40"}}
I have managed to check is student already registered to course with this code:
Object.keys(registeredcoursesobject).forEach(function(key){
if( Object.keys(coursestoregisterobject).includes(key)) {
alert("You have already registered to "+key+" crn number course");
//return;
}
});
A course can be at most 2 days in a week and in 1 different time intervals(what if 2 time intervals??) which means that there will be only one "-" in days property and only one "*" in hours property.
I am new to programming and working on this for days any ideas ?

I hope this answer is still relevant for you. Here is what I have:
var registeredcoursesobject = {"00001":{"days":"Monday-Thursday","hours":"11:40-12:30*16:30-18:30"}}
var coursestoregisterobject = {"00002":{"days":"Monday-Friday","hours":"10:40-15:30*16:40-18:00"}}
var getTicks = function(timeStr) {
return new Date('1970-01-01T' + timeStr + ':00Z').getTime();
}
Object.keys(registeredcoursesobject).forEach(function(rKey){
if( Object.keys(coursestoregisterobject).includes(rKey)) {
alert("You have already registered to "+rKey+" crn number course");
return false;
};
Object.keys(coursestoregisterobject).forEach(function(cKey){
var regDays = registeredcoursesobject[rKey].days.split('-');
var regHours = registeredcoursesobject[rKey].hours.split('*');
var courseDays = coursestoregisterobject[cKey].days.split('-');
var courseHours = coursestoregisterobject[cKey].hours.split('*');
regDays.forEach(function(rDay, i) {
var rHourRange = regHours[i];
// I assume you need to check there is same date/time pain in registeredcoursesobject and coursestoregisterobject
courseDays.forEach(function(cDay, j) {
if (rDay == cDay) {
var cHourRange = courseHours[j];
// now, do you need to compare hours be equal exactly or do you need to check time overlap?
// assume you just need to ckeck hour ranges are equal, then:
if (rHourRange == cHourRange){
// means equal
alert("You have already registered to "+cKey+" crn number course on day "+cDay+" at "+cHourRange+" hours.");
return true;
}
// if you need to check range overlap
var rTime = rHourRange.split('-');
rTimeRange = [getTicks(rTime[0]), getTicks(rTime[1])];
rStartT = Math.min.apply(null, rTimeRange), rEndT = Math.max.apply(null, rTimeRange);
var cTime = cHourRange.split('-');
cTimeRange = [getTicks(cTime[0]), getTicks(cTime[1])]
cStartT = Math.min.apply(null, cTimeRange), cEndT = Math.max.apply(null, cTimeRange);
// now your rangeTime is a pair of int values, that represent time range rStartT:rEndT
// and your courseTime is a pair of int values cStartT:cEndT
// so now you just check the overlap of two integer pais.
// according to this: https://stackoverflow.com/questions/3269434/whats-the-most-efficient-way-to-test-two-integer-ranges-for-overlap#answer-3269471
if (rStartT < cEndT && cStartT < rEndT) {
alert("You have already registered to "+cKey+" crn number course on day "+cDay+" within time range "+cHourRange+" hours overlap with "+rHourRange+" time range.");
// means time ranges are overlap at some range. But I don't count the border, like "14:00-15:00" and "15:00-16:00" do not overlap
// otherwise replace < with <=
return true;
}
}
})
});
return false;
});
});
I am making some assumptions here about your task.
UPDATE: added time range check.
UPDATE: check keys equal first and values swap if start time is for some reason is bigger than end time.

Related

Javascript inheritance - asking experts oppinion on the following code

A friend of mine is attending a JavaScript course and thinks that the code he is submitting for grading is correct. However, the grader support keeps reporting it as not correct. He asked for my help and I tested the code on several IDEs and editors, online and offline, and I also got back every time a correct evaluation.
However I don't use often JavaScript ans I'm hesitating to answer my friend that he is right.
I would be most grateful if someone with more experience could tell me if the code evaluates correctly or not. Thank you.
"Determines which day of the week had the most nnumber of people visiting the pet store.
If more than one day of the week has the same, highest amount of traffic, an array containing the days (in any order) should be returned.
(ex. ["Wednesday", "Thursday"]).
If the input is null or an empty array, the function should return null.
#param week an array of Weekday objects
#return a string containing the name of the most popular day of the week if there is only one most popular day, and an array of the strings containing the names of the most popular days if there are more than one that are most popular"
function Weekday (name, traffic) {
this.name = name;
this.traffic = traffic;
}
function mostPopularDays(week) {
// IMPLEMENT THIS FUNCTION!
this.week = week;
if (typeof week !== 'object' || week === null || week === undefined || week.length === 0) {
return null;
}
var maxTr = 0;
var maxTrDay = [];
for (var i = 0; i < this.week.length; i++) {
if (this.week[i].traffic > maxTr) {
maxTrDay = [this.week[i].name];
//maxTrDay = this.week[i].name;
maxTr = this.week[i].traffic;
} else if (this.week[i].traffic === maxTr) {
//maxTrDay = [this.week[i].name];
maxTrDay.push(this.week[i].name);
} else if (this.week.length > 7) {
this.week.shift();
}
}
if (maxTrDay.length === 1) {
console.log("The most popular day of the week was:")
return maxTrDay[0];
} else if (maxTrDay > 1) {
console.log("The most popular days of the week were:")
return maxTrDay;
}
return null;
}
The test case that the grader reports as failed are the following:
1. mostPopularDays should return an array of days when more than one day has most popular traffic
I used the following lines for testing, and the output was always the last (commented) line below:
var week = [];
var sun = new Weekday('Sunday', 100); week.push(sun);
var mon = new Weekday('Monday', 90); week.push(mon);
var tue = new Weekday('Tuesday', 100); week.push(tue);
mostPopularDays(week);
// [Sunday, Tuesday]
The issue is (maxTrDay > 1) is comparing an array object with the number 1. This will be false for all array inputs except for, confusingly, e.g. ([2] > 1), but that's JS for you.
Running your code as-is with the provided driver (with added quotes to Tuesday to avoid a ReferenceError) yields the output of null.
Your friend probably means (maxTrDay.length > 1), which compares based on length and yields the correct output:
The most popular days of the week were:
=> [ 'Sunday', 'Tuesday' ]

How can I add leading zero if my value is less than 10? Using node JS

how can I add leading zero to my column when my column's value is less than 10?
here is my code:
db.all("SELECT * FROM tablename WHERE x= ? ORDER BY MEMBER_CODE DESC LIMIT 1",[x], function(err,rows) {
if(rows.length == 0)
{
var mcode = 0;
}
else
{
var mcode = rows[0].MEMBER_CODE;
if (mcode < 10) {
mcode = "0"+mcode;
console.log(mcode);
}
} db.run("INSERT INTO f11 MEMBER_CODE VALUES $MEMBER_CODE",{ $MEMBER_CODE : +mcode+1});
From the code, MEMBER CODE increments every input. I tried that code but it fails. the output of console.log(mcode) which appends zero less than 10 is the one i want but it doesnt append zero anymore when the data will be processed on the database
console.log(mcode) outputs 01,02,03,04,05,06,...,10++
BUT
+mcode+1 outputs 1,2,3,4,5,6,...,10++
Please bear with my question and my explanation. Thanks

Trouble with Loop and Functions in Javascript

So i have an assignment and ive been doing it now for a few hours and am very stuck on a few parts of it. So the parts im stuck on is having to use a loop to validate information put into a prompt, and using information from an array to coincide with with a variable in another function and finally displaying all of it.
So I have everything set up but have no idea what exactly im getting wrong here if someone would mind helping point me in the right direction? Oh I should probably mention Im trying to get the second function to go with the array so when the user enters a number (1 through 4) it matches with the prices in the array.
function numSeats() {
//var amountSeat=document.getElementById("price");
var amountSeat=prompt("Enter the amount of seats you would like");
amountSeat=parseInt(amountSeat);
for (i=7; i<amountSeat; i++){
if (amountSeat<1 || amountSeat>6) {
alert("Check the value of " + amountSeat);
location.reload(true);
}else{
alert("Thank You");}
}
return amountSeat;}
function seatingChoice() {
//var seatChoice=document.getElementById("table").innerHTML;
var seatChoice=prompt("Enter the seat location you want.");
seatChoice=parseInt(seatChoice);
for (i=7; i<seatChoice; i++){
if (seatChoice<1 || seatChoice>4) {
alert("Check what you entered for " + seatChoice);
location.reload(true);
}else{
alert("Thank You")}
}
return seatChoice;}
var price=new Array(60, 50, 40, 30);
var name=prompt("Please enter your name.");
if (name==null || name=="")
{
alert("You did not enter a name, try again");
location.reload(true);
}
else
{
alert("Thank You");
}
document.write(name + " ordered " + numSeats() + " for a total dollar amount of " + seatingChoice(
) );
It looks to me like you repeat the same error in both numSeats and seatingChoice;
Let's look at what you're doing with your loop
var amountSeat = prompt("Enter the amount of seats you would like");
for (i=7; i<amountSeat.length; i++) {/* amountSeat[i] */}
prompt asks the client for a String, so amountSeat is a String.
amountSeat.length is thus the number of characters in the String.
You start your loop at i = 7, thus amountSeat[i] starts from the 7th character in the amountSeat (assuming there are at least 7 characters in amountSeat)
It looks to me more like you want to get a number from the prompt;
// string
var amountSeat = prompt("Enter the amount of seats you would like");
// to number
amountSeat = parseInt(amountSeat, 10); // radix of 10 for base-10 input
Next, consider your if
if (amountSeat[i]<1 && amountSeat[i]>6) {
This is saying if less than 1 AND more than 6. No number can be both of these states at the same time, so it will always be false. It looks like you wanted to use an OR, ||
// do your check
if (amountSeat < 1 || amountSeat > 6) { /* .. */ }
Finally, it looks like you want to calculate the price by some logic, which you haven't included. However, I'm sure it will be based upon numSeats and seatingChoice so you will need to keep a reference to these choices.

compare start "Time" is less than the end "Time" in javascript

I have a value in two text fields which is already formatted as hh:mm, How can I compare the values of these two fields?
I am trying the following code:
function check_ToFromTime(toTime) {
if (getControl('txtStartTimeFrom').value == '00:00' && getControl(toTime).value == '00:00') { return true; }
var fromDate = new Date(getControl('txtStartTimeFrom').value);
var toDate = new Date(getControl('txtEndTimeTo').value);
var fromT = fromDate.getTime();
var toT = toDate.getTime();
return (toT >= fromT);
}
the if statement in the first line works, but the last statement
return (toT >= fromT);
does not work. it always returns false. where am i going wrong?
I wouldn't worry about converting these String objects to Date objects. Just split the string and compare:
var fromDate = "04:05";
var toDate = "04:04";
var fromTokens = fromDate.split(":");
var toTokens = toDate.split(":");
alert(fromTokens[0] < toTokens[0] || (fromTokens[0] == toTokens[0] && fromTokens[1] < toTokens[1]));
You could place this functionality in a nice function for re-usability:
function isAfter(fromDate, toDate){
var fromTokens = fromDate.split(":");
var toTokens = toDate.split(":");
return (fromTokens[0] < toTokens[0] || (fromTokens[0] == toTokens[0] && fromTokens[1] < toTokens[1]));
}
//Tests
alert(isAfter("04:04", "05:05"));
alert(isAfter("06:04", "05:05"));
alert(isAfter("05:05", "05:05"));
JS Fiddle: http://jsfiddle.net/X5v5F/
I'm not going to head down this route, since I think splitting the strings is sufficient, but if you were fixed on a date, I would recommend using Moment.js.
it will always print false because end time will always be greater than start time.U need to change the condition i.e. return (toT <= fromT);

Javascript : function checking if the answer to score as a percentage has more than 2 decimal places

I want to create a dynamic worksheet for my students, so every time they do it they see different questions. The question that I am trying to create ie, calculate the percentage if I scored X out of a total of Y.
Here are the 3 functions which work together, the first generates some numbers, calls the second, which in turn calls the third to check if it more than 2 decimal places, then if it is, the second creates a new SCORE number which repeats until it finds an answer which is 2 decimal places or less, then returns the SCORE number which works to the first, which outputs it.
I keep getting one of three outputs : undefined where the SCORE should be, no output at all, or a working question.
I cannot understand how it works sometimes, throws undefined sometimes and gives completely nothing at other times.
Any ideas.
function scorePercent()
{
var output="";
var total = Math.floor((Math.random()*99)+1);
var score = Math.floor((Math.random()*(total-1))+1);
output = output + "<div>A score of " + chkScore(score,total) + " out of " + total + ".</div></br>";
document.getElementById("qOut").innerHTML=output;
}
function chkScore(n1,n2)
{
var answ = (n1/n2)*100;
if(dps(answ)>2)
{
var scoreNew = Math.floor((Math.random()*(n2-1))+1);
chkScore(scoreNew, n2);
}
else
{
return n1;
}
}
function dps(num)
{
var match = (''+num).match(/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/);
if (!match) { return 0; }
return Math.max(
0,
// Number of digits right of decimal point.
(match[1] ? match[1].length : 0)
// Adjust for scientific notation.
- (match[2] ? +match[2] : 0));
}
You have a recursive function in your chkScore, but you're not return-ing the results from the "deeper" iterations.
Try this:
function chkScore(n1,n2){
var answ = (n1/n2)*100;
if(dps(answ)>2) {
var scoreNew = Math.floor((Math.random()*(n2-1))+1);
return chkScore(scoreNew, n2); // <-- return that.
} else {
return n1;
}
}
The missing return there, resulted in the function sometimes not returning anything.
The "deeper" iterations will return their value only 1 "level" up, so that "level" will have to pass it through, if you know what I mean.

Categories

Resources