I'm working on a tuition calculator for students and updating it to reflect the current year, in changing the year, every time the #variable option is selected to Variable (inherited code, not my choice of name) the output duplicates all of the fees. I've revised the functions, and code, where is this issue arising?
(my current version with issues: https://tarleton.edu/scripts/tuitioncal/default-trial.asp)
At first I thought it was a year issue, but after reading through previous documentation, I corrected it but issue is still arising.
I'm assuming that the issue arises here and that it runs through this if/else statement twice, though the information is not changing:
$('input#submit').click(function() {
var currentDate = new Date();
var currentYear = currentDate.getFullYear(); //Currently in the middle of
the academic year, so the adjustment had to be made.
var adjustedYear = 0;
var adjustmentForYear = 0;
if ($('select#semester option:selected').hasClass('current-academic-year')){ adjustmentForYear = parseInt(-1); }
else if ($('select#semester option:selected').hasClass('future-academic-year')) { adjustmentForYear = parseInt(0); }
else if ($('select#semester option:selected').hasClass('last-year')) { adjustmentForYear = parseInt(-2); }
if ($("select#variable option:selected").val() != "variable" || $('select#classification option:selected').val() == "4")
{
//Handles ALL Guaranteed Tuition Plans and Graduate Plan
adjustedYear = (parseInt($('select#semester option:selected').val()) +
adjustmentForYear - $('select#classification option:selected').val());
}
else
{ //Handles Variable Tuition Plans for Freshmen, Sophomores, Juniors, and Seniors
adjustedYear = currentYear + adjustmentForYear;
}
I expect a non duplicated output that includes University Services fee to be $91.66, but instead see University Services fee: $991.66 AND $117.89.
Related
The problem I am trying to solve in Google Sheets is as follows:
add 180 days to whichever date passes my conditional test to every single row in a certain column based on 3 dates.
Google Sheets Example
I came up with the following script:
function adjustDates() {
var app = SpreadsheetApp;
var activeSheet = app.getActiveSpreadsheet().getActiveSheet();
for(var i=2; i<5; i++) {
var updatedCell = activeSheet.getRange(i, 2).getDate;
var removedCell = activeSheet.getRange(i, 4).getDate;
var implementedCell = activeSheet.getRange(i, 1).getDate;
if (updatedCell == null && removedCell == null){
activeSheet.getRange(i, 3).setValue(implementedCell+180);
} else if (updatedCell != null){
activeSheet.getRange(i, 3).setValue(updatedCell+180);
} else {
activeSheet.getRange(i, 3).setValue(removedCell+180);
}
}
}
I think I nailed down the logic, but I can't figure out why I am getting #NUM! error in all of my rows. I don't need to worry about leap years so this was a brute force solution on my part.
I am very new to JavaScript so please be gentle.
Thanks!
There is no such thing as getDate in class range.
You need to get the value first via getValue, and then as Matriarx mentioned, set the date using date.setDate(date.getDate() + 180)
var implementedCell = activeSheet.getRange(i, 1).getValue();
// we make sure to cast the date properly to avoid unexpected errors
var iCellDate = new Date(implementedCell);
iCellDate = iCellDate.setDate(iCellDate.getDate() + 180)
activeSheet.getRange(i, 3).setValue(iCellDate);
Apply to all instances.
new Date(date.getFullYear(),date.getMonth(),date.getDate() + 180)
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' ]
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.
I have this survey application that stores when my respondents have taken my survey using a JavaScript timestamp (ex 2015-06-18T10:35:26.980Z)
What I need to find out is how many respondents have taken the survey daily. I'm not very sure how to compare the dates daily starting from, for example, 2 years ago. Any pointers how I should proceed?
So far I have an array of the date/time when my respondents took the survey. Many thanks!
Edit:
Code so far.
var dateCounter = {};
timeStart.forEach(function(date) {
var key = date.toISOString().split('T')[0];
dateCounter[key] = dateCounter[key] || 0;
dateCounter[key] += 1;
});
console.log(dateCounter);
Quick and dirty snippet
var dateCounter ={};
dateArray.forEach(function(date) {
var key = date.toISOString().split('T')[0];
dateCounter[key] = dateCounter[key] || 0;
dateCounter[key] += 1;
});
At the end of this, dateCounter should have a bunch of totals for each date
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
Right, i was uncertain if I should post this as it is a little vague but I really would like some help with this so I will try explain as best as possible.
The Idea:
To create a text based game using Javascript/jQuery, the game will be that of one where a story is being told and you get to pick the options.
My idea was to use a textarea to allow input from the user (select a option) and output text (from the story).
How far have I got?
Well this is what I have created so far.
JavaScript/jQuery:
var current, text, location, option1, option2;
location = ''; // house, car, moon
current = 0;
gameOver = false;
pick = false;
jQuery("textarea").keypress(function (e) {
if (e.which == 13) {
var content = this.value;
var lastLine = content.substr(content.lastIndexOf("\n") + 1);
// Story
if (current == 0 && pick == false) {
option1 = 'Look around';
option2 = 'Check you have arms (Check arms)';
text = 'You open your eyes \n\nOptions: \n' + option1 + '\n' + option2;
pick = true;
} else if (current == 0 && lastLine == 'Check arms' && pick == true) {
text = 'You check your arms, they seem fine';
pick = false;
} else if (current == 0 && lastLine == 'Look around' && pick == true || current == 2 && lastLine == 'Get Out') {
option1 = 'Walk to a nearby house';
option2 = 'Get in a rocket that is next to you (Get in rocket)';
text = 'You do a 360 spin, you see you have limited options \n\nOptions: \n' + option1 + '\n' + option2;
pick = false;
if (current == 2 && lastLine == 'Get Out') {
current = 1;
} else {
current++;
}
}
//House Story
else if (current == 1 && lastLine == 'Walk to house' && pick == false) {
option1 = 'Knock on the front door';
option2 = 'Jump through the front window';
text = 'You walk to the house and see there are no lights on, the building is old and appears to be burnt out\n\nOptions: \n ' + option1 + '\n ' + option2;
pick = false;
current++;
}
// Rocket story
else if (current == 1 && lastLine == 'Get in rocket' && pick == false) {
option1 = 'Get out of the rocket(Get out)';
option2 = 'Hit the biggest button you can find(Hit Button)';
text = 'You hop into the rocket, there are a lot of buttons infront of you\n\nOptions: \n ' + option1 + '\n ' + option2;
pick = false;
current++;
}
$('textarea ').val($('textarea ').val() + '\n\n ' + text + '\n ');
}
});
It works (kinda) but it is getting complicated to code like this. To me its very messy and I have tried to re-write it but I cannot find a way to make this neat/ easier to code.
Have a look at the demo:
Please do take a look at the demo if you wish to try and help me as you will get a good idea what I am trying to achieve.
Demo walk-through:
DEMO HERE
In the textarea click enter to start
Type one of the options to progress in the game (Options: Check arms or Look around)
Type one of the options to progress in the game (Options: Walk to a nearby house or Get in rocket)
End of demo
Note: After typing a option click enter to continue. At the moment all options must be typed exactly as seen (If option has brackets you type that instead)
This is a short demo but you should get the point. I have searched around and cant find/think of a suitable method to code this game.
Get to the point, what's the question?
My questions is: What is a suitable method to code this game?
Suitable: Easy to maintain/read + add new story "parts" etc.
I would go with some kind of strategy pattern. Create i.e. a Game constructor
var Game = new function(strategy) {
this.strategy = strategy;
}
Game.prototyp.playScene = function() {
return this.strategy();
}
Then you can create scenes where you would place your logic
var sceneOne = function() {
console.log('First scene logic here');
}
var sceneTwo = function() {
console.log('Second scene logic here');
}
and finally you can call these logics as follows:
var game;
if(e.which == 13) {
if(condition1) {
game = new Game(sceneOne);
} else {
game = new Game(sceneTwo);
}
game.playScene();
}
fiddle
The biggest issue I see here is that your code is going to grow and grow as your game/story expands. You're actually writing the logic of your game in the code itself.
As an alternative I would suggest splitting out your logic into steps and logic. For example:
var allTiles =
[
{location: 'Forest', description: 'Deep, dark and scary'},
{location: 'Castle', description: 'High, made from stone and very dramatic'},
];
var currentState =
{
equipment: ['Sword', 'Bow', '3 gold coins'];
currentLocationIndex: 0
};
These may of course be in different files so you can add locations to your world.
Next you need your core logic class, this will look a lot like the one you've already got:
jQuery("textarea").keypress(function (e) {
var currentLocation = allTiles[currentState.currentLocationIndex];
printDescription(currentLocation.Description);
// process commands... into pseudo code territory
if(userDoesAction1){
currentLocation.doAction1();
}
}
I've not gone into massive detail here - it will depend very much on the structure of your game. Personally I like the idea of creating an array functions in your location which are things you can do at your location... actually, JS is a very nice language to do this sort of game!
You can use my jQuery terminal. Then you can write core of the game that act on data in JSON object. If you write something like this you will be able to change the data (update or replace) without need to change the code, it's called data driven programming (Eric Raymond write nice chapter in his book about it)
When making games i think that an Object Oriented approach is the best to keep things separated and easy to code and find:
For example you could separate the different rooms in your game in different function structures.
var parentFunction = function(){
var protectedValue = ‘variable’;
var childFunction = function(){
alert(protectedValue);
}
childFunction();
}
var object = new parentFunction();
You initialize the function every time you move to the related ambient, and put the possible actions that the player can take in child-functions.
But i guess the answer would be too big here: you should spend some time before starting to make a scheme of the logic that your game will follow and how you want to separate things (and how they relate to each other).