Javascript in googlespreadsheets - javascript

I am trying to create a counter that counts the cells that include in their content the date before today as a date. However the result in cell 16,1 is always zero as it seems that my loop does not work. I know I can do it with a formula in spreadsheets but I want to use javascript. Also I am trying to find out what is wrong in MY code.
I have wrirtten the following lines of code:
function job_counter() {
var yesterday_jobs=0;
var ss=SpreadsheetApp.getActiveSpreadsheet().getActiveSheet()
var e = new Date(new Date().getFullYear(),new Date().getMonth() , new Date().getDate())
var yesterday = new Date(new Date().getFullYear(),new Date().getMonth() , new Date().getDate())
yesterday.setDate(yesterday.getDate() - 1);
var range_unformated=ss.getRange(2,3,25).getValues()
var date;
for (var i=1; i<25; i++){
date=Date.parse(range_unformated[i])
Logger.log(date[3])
if ( date[i] - yesterday.getTime() >= 0 && date[i] != "" ){
yesterday_jobs = yesterday_jobs + 1
ss.getRange(16,2).setValue(yesterday_jobs)
}}
// check yesterday_jobs
}

This will solve your problem, it uses getValues getting a range of 24x24 cells and iterating it to compare every cell value to see if it is equal to yesterday:
function isYesterday(){
var yesterday_jobs=0;
var ss=SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var row=0;
var col=0;
var date;
var yesterday = new Date(new Date().getFullYear(),new Date().getMonth() , new Date().getDate())
yesterday.setDate(yesterday.getDate() - 1);
range = ss.getRange(1,1,25,25).getValues()
for (var i = 0; i < 25; i++){
for ( var j = 0; j < 25; j++) {
date = Date.parse(range[i][j]);
if ( date - yesterday.getTime() <= (24 * 60 * 60 *1000) ){
yesterday_jobs = yesterday_jobs + 1;
}
}
}
ss.getRange(16,2).setValue(yesterday_jobs);
}
Things that were wrong...
This is wrong and it is the reason it's not working:
yesterday_jobs === yesterday_jobs + 1;
You should be doing:
yesterday_jobs = yesterday_jobs + 1
Why?
Because == and === are Comparison operators, and = is an assignment operator.
What you are trying to do is to set a new value to yesterday_jobs, not to compare it, so you have to use =.
This will solve your problems with the loop assignations.
When doing a = 2 you are assigning a value to a variable:
a value is now equal to 2 value
When doing a == 2 you are asking:
Is a equal to 2 in value?
When doing a === 2 you are asking
Is a equal to 2 in value and type?

The example below shows how to retrieve and log the items names and items numbers.
function logItemstInfo() {
var sheet = SpreadsheetApp.getActiveSheet();
var data = sheet.getDataRange().getValues();
for (var i = 0; i < data.length; i++) {
Logger.log('Items name: ' + data[i][0]);
Logger.log('Items number: ' + data[i][1]);
}
}

Related

*Calendar Program* Having trouble writing a loop for this calendar program to display properly

I am having an issue trying to complete my code. I am trying to get the code to print the arrays in several different rows. It is suppose to look like this:
Ok, here is the updated code. I have been working on it and it is getting better! However, my issue now is trying to figure out what I need to do in order to create blank spaces where the "0" and "1" are currently in the output of the code. I think I just need to insert:
calDaysOfWeek.unshift();
or possibly:
calDaysOfWeek.shift();
I just cannot figure out where to put it. If I can figure that out, I should be able to make the days in my code less abbreviated (Such as M to Mon or T to Tues).
/*Write a program called calendar.js that displays a calendar month
for May 2012 as the month and year. You must use a loop. The format
of the month should be as shown below: Hint: You can't use console
log and print on the same line. Try storing the entire row as one
concatenated string and then displaying it. You must use loops for
this one. Do not just print the calendar as a series of console.log
statements!*/
calDaysOfWeek = [];
calDaysOfWeek.push("Sun", "Mon", "Tues", "Wed", "Thur", "Fri", "Sat");
var s = "MAY 2012\nS M T W T F S\n";
var numDaysOfWeek = calDaysOfWeek.length;
var firstDay = 2;
var numDaysOfMonth = 31;
var numWeeks = numDaysOfMonth/7;
for(var i = 0; i < numWeeks; i++) {
for(var j = 0; j < numDaysOfWeek; j++) {
s += i*numDaysOfWeek + j + ' ';
}
s += "\n";
}
if (firstDay != calDaysOfWeek[2]) {
calDaysOfWeek.push();
}
else if (calDaysOfWeek[30] != 31) {
calDaysOfWeek.pop();
}
else
console.log(s);
You have an error here:
for(var i = 0; len = calDaysOfWeek.length; i < len; i++)
It should be:
len = calDaysOfWeek.length;
for(var i = 0; i < len; i++) {
}
Now, you need to use this loop to fill your string rather than using arrays. So:
var s = "";
len = calDaysOfWeek.length;
for(var i = 0; i < len; i++) {
}
But your loop is only going from 0 to 6 since you have 7 days of week. So you need another loop for the weeks. Something that you cannot compute easily is the first day of the month which is a Tuesday, so it's indice in calDaysOfWeek is 2 (Sun=0, Mon=1, Tue=2). You also need the number of days in the month, here 31.
var s = '';
var numDaysOfWeek = calDaysOfWeek.length;
var firstDay = 2;
var numDaysOfMonth = 31;
var numWeeks = ??? // compute this
for (var i=0; i<numWeeks; i++) {
for (var j=0; j<numDaysOfWeek; j++) {
s = ??? // you need to do this
}
}
Once the result is correct you can display it by using html code that you will print.
Edit: changed the loops
Edit2: played with it on fiddle
calDaysOfWeek = [];
calDaysOfWeek.push("Sun", "Mon", "Tues", "Wed", "Thur", "Fri", "Sat");
var s = "MAY 2012\n";
var numDaysOfWeek = calDaysOfWeek.length;
var firstDay = 2;
var numDaysOfMonth = 31;
var numWeeks = 5; // compute this
for (var i=0; i<numWeeks; i++) {
for (var j=0; j<numDaysOfWeek; j++) {
var n = i * numDaysOfWeek + j + 1 - firstDay ;
if (n < 1 || n > numDaysOfMonth) {
s += ' '; // three spaces
}
else {
if (n < 10)
{
s += ' '; // pad with one space
}
s += n + ' ' ;
}
}
s += "\n";
}
alert(s);

Array of Date with for loop

I have problem with this code. If I print item of daysArray in for loop (console.log(daysArray[i]);) it returns right date, but after for loop returns last date at all daysArray items.
Please some could help me.
public getFullMonth(date: Date): Array<Date> {
var firstDay = this.getSunday(date);
var daysArray: Array<Date> = Array<Date>();
for (var i = 0; i < 43; i++) {
firstDay.setDate(firstDay.getDate() + 1);
daysArray[i] = firstDay;
console.log(daysArray[i]);
}
console.log(daysArray.length);
console.log(daysArray[0]);
console.log(daysArray[30]);
return daysArray;
}
The problem is that you always use the same instance of Date, you never create a new one, so all of the items in daysArray are the same exact instance.
Because of that, when you do:
firstDay.setDate(firstDay.getDate() + 1);
Then you actually change the value for all items.
You should create a new instance for every item:
public getFullMonth(date: Date): Array<Date> {
var firstDay = this.getSunday(date);
var daysArray: Array<Date> = Array<Date>();
for (var i = 0; i < 43; i++) {
firstDay = new Date(firstDay.getTime());
firstDay.setDate(firstDay.getDate() + 1);
daysArray[i] = firstDay;
console.log(daysArray[i]);
}
console.log(daysArray.length);
console.log(daysArray[0]);
console.log(daysArray[30]);
return daysArray;
}
Notice that each iteration now does:
firstDay = new Date(firstDay.getTime());
Which creates a new instance of Date which is a "clone" of the previous one.
Your problem is easy to solve. You are just copying the same item in each position of the array. These means you are overriding the value you set in each step of the for loop.
Just create a new object for each position of the array and you won't have the error any more. Something like this
for (var i =0; i < 43; i++) {
var nDay = new Date();
nDay.setDate(firstDay.getDate() + i + 1);
daysArray[i] = nDay;
console.log(daysArray[i]);
}

Javascript date array, filling in missing days incrementaly

I'm trying to display a graph with Flot. My data array does not have a date set if there is no value for that date. I've followed the accepted answer in this question to 'fill in the gaps', but I now want the value to be the last value, and not 0. I can't get my head around how to get the previous date's value. I've tried getting the previous value with var previousTotal = date[i][1];, but I can't seem to get the right part of the array no matter what I try.
Can anyone help please?
function fillInGapsAdding(data) {
var startDay = data[0][0],
newData = [data[0]];
// Loop through all items in array
for (i = 1; i < data.length; i++) {
var diff = dateDiff(data[i - 1][0], data[i][0]);
var startDate = new Date(data[i - 1][0]);
if (diff > 1)
{
for (j = 0; j < diff - 1; j++)
{
var fillDate = new Date(startDate).setDate(startDate.getDate() + (j + 1));
var previousTotal = date[i][1];
newData.push([fillDate, 0]);
}
}
newData.push(data[i]);
}
return newData;
}
After a bit more work, I figured it out....
var previousTotal = data[i][1];

What is the most efficient way of finding missing dates within a daterange

Let's say I have an array of N dates:
var dates = ['2013-01-01', '2013-01-02', '2013-01-05' ...]
What is the quickest way to find all the missing dates between the first date and the last? (let's assume that the dates are sorted from earliest to latest).
The gap is not consistent and could be at any size.
I rather not use any libraries, just pure javascript.
Generally if you have two sorted arrays and want to find the items in one missing from the other you would iterate over both in paralel. My solution is similar to that one, but uses a generator over the date array:
function DateIterator(date){
this.current = date;
}
DateIterator.prototype.next = function() {
this.current.setDate(this.current.getDate() + 1);
return this.current.getFullYear() + '-' +
(this.current.getMonth()+1) + '-' +
this.current.getDate();
};
var dates = ['2013-1-1', '2013-1-2', '2013-1-5' ,'2013-2-2'];
var di = new DateIterator(new Date(dates[0]));
var date, missing = [];
for (var i=1; i<dates.length; i++) {
while ((date = di.next()) !== dates[i]) {
missing.push(date);
}
}
console.log(missing);
Note that the check for dates is made by comparing the string values. The dates returned by next are not 0-padded so a comparison between 2013-01-01 and 2013-1-1 would fail. This can be solved by making a smarter comparison function, but i consider it beyond the scope of the question.
I would do a date diff, and generate new dates for any missing ones, like this:
var dates = [new Date(2013,1,1), new Date(2013,1,2), new Date(2013,1,5)];
var missingDates = [];
for (var i = 1; i < dates.length; i++)
{
var daysDiff = ((dates[i] - dates[i - 1]) / 86400000) - 1;
for (var j = 1; j <= daysDiff; j++)
{
var missingDate = new Date(dates[i - 1]);
missingDate.setDate(dates[i - 1].getDate() + j);
missingDates.push(missingDate);
}
}
console.log(missingDates);
JSFiddle

Get the next highest date value after excluding values from an array

I have a myDate variable with the value 18-Nov-2013.Each day its value is being changed.Tommorow this myDate variable will have the value 19-Nov-2013.I have a list of values that i have mapped into a single array named exclude which contains some dates that are to be excluded ,now it has values ["20-Nov-2013",21-Nov-2013", "23-Nov-2010"] .How could i filter my value from the list of values from the exclude array.I need the next highest value from the array.So here i need the value 22-Nov-2013 after tommorrows date.Could someone help me with this.
var excluded = ["30-Nov-2013","01-Dec-2013","02-Dec-2013"];
var myDate = "29-Nov-2013";
var month = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
var current = new Date(myDate);
while(true){
current = new Date((current.getDate()+1<10? "0"+(current.getDate()+1):(current.getDate()+1))+ "-" + month[current.getMonth()] + "-" + current.getFullYear());
var checkDate = (current.getDate()<10? "0"+(current.getDate()):(current.getDate()))+ "-" + month[current.getMonth()] + "-" + current.getFullYear();//this is necessary for when the +1 on day of month passes the month barrier
if(-1 == excluded.indexOf(checkDate))
break;
}
alert(checkDate);
I don't know if this is the best approach, or if is the best algorithm, but you may try this:
var myDate = ["17-Nov-2013", "18-Nov-2013"];
var excluded = ["20-Nov-2013", "21-Nov-2013", "23-Nov-2013"];
var months = {"Nov": 10}; // Add others months "Jan": 1, "Fev": 2 etc...
function findExcluded(date)
{
for (var i = 0; i < excluded.length; i++)
{
if (excluded[i] === date)
{
return true;
}
}
return false;
}
function nextDate()
{
var last = myDate[(myDate.length - 1)];
var s = last.split("-");
var d = new Date(s[2], months[s[1]], s[0]);
var next = new Date(d);
var chkDate = "";
do
{
next.setDate(next.getDate() + 1);
chkDate = next.getDate() + "-" + findMonth(next.getMonth()) + "-" + next.getFullYear();
} while(findExcluded(chkDate));
return chkDate;
}
function findMonth(m)
{
var i = 10; // When you fill all months on 'months' array, this variable should start at '0' in order to loop to works.
for (var month in months)
{
if (i == m)
{
return month;
}
i++;
}
}
var nd = nextDate();
alert(nd);
See it woring here.
No code ? Well here will be my method:
1.Get next date for mydate. Say that is var nextDate.
2.Check whether that date exist in the array.
3.If exists add one more day to nextDate. Again check in the array.
4.Do it until you get a date which is not present in your exclude array
For checking whether it exists in the array you can use arrValues.indexOf(nextDateInProperFormat) > -1

Categories

Resources