How to use the parameter (yearSlipt) of the first function to the second function for i can make the difference between year entered by user and the current year.
function checkDate(date,anneSplit){
var date = new Array();
for(i = 0; i < 3 ; i++){
date[i] = prompt("entrer un date dd/mm/yyyy : ");
console.log(date[i]);
}
for(var i = 0; i < date.length ; i++)
{
daySplit = parseInt(date[i].split("/")[0]);
monthSplit = parseInt(date[i].split("/")[1]);
yearSplit = parseInt(date[i].split("/")[2]);
}
return (daySplit,monthSplit,yearSplit);
console.log(daySplit,monthSplit,yearSplit);
}
function age(ageToday,yearSplit){
checkDate();
var ageToday = new Array();
var d = new Date();
var year = d.getFullYear();
console.log(year);
ageToday = year - yearSplit;
document.write(ageToday);
}
for multi return values, you could use array or json object.
function checkDate(date, anneSplit) {
var date = new Array();
for (i = 0; i < 3; i++) {
date[i] = prompt("entrer un date dd/mm/yyyy : ");
console.log(date[i]);
}
for (var i = 0; i < date.length; i++) {
daySplit = parseInt(date[i].split("/")[0]);
monthSplit = parseInt(date[i].split("/")[1]);
yearSplit = parseInt(date[i].split("/")[2]);
}
return {
daySplit: daySplit,
monthSplit: monthSplit,
yearSplit: yearSplit
};
}
function age(ageToday, yearSplit) {
var checkResult = checkDate();
console.log(checkResult.yearSplit);
// var ageToday = new Array();
// var d = new Date();
// var year = d.getFullYear();
// ageToday = year - yearSplit;
//document.write(ageToday);
}
age();
the problem : the function return only one date but it was 3 dates entred by user
function checkDate(date) {
var date = new Array();
for (i = 0; i < 3; i++) {
date[i] = prompt("entrer un date dd/mm/yyyy : ");
console.log(date[i]);
}
for (var i = 0; i < date.length; i++) {
daySplit = parseInt(date[i].split("/")[0]);
monthSplit = parseInt(date[i].split("/")[1]);
yearSplit = parseInt(date[i].split("/")[2]);
}
return {
daySplit: daySplit,
monthSplit: monthSplit,
yearSplit: yearSplit
};
}
function age(yearSplit) {
var checkResult = checkDate();
var ageToday = new Array();
var d = new Date();
var year = d.getFullYear();
for(var i = 0; i < 3 ;i++)
{
ageToday[i] = year - checkResult.yearSplit;
console.log(ageToday);
}
}
age();
Related
I'm starting to learn about google app script with JavaScript.
I wrote this code, but it is really slow and executing the function takes too long. I think this isn't the best way to do the function.
Is there any option/way (array), to make it faster or in other way to reduce to the time waiting?
All I wish to do is to insert "today's date", when a column cell value is set true, in another cell column.
function onEdit() {
sConfDate();
}
function sConfDate(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var dataSheet = ss.getSheetByName("Data");
var dataRange = dataSheet.getRange(9, 1, dataSheet.getLastRow(), 43);
var data = dataRange.getValues();
var d = new Date();
var dd = d.getDate();
var mm = d.getMonth() +1;
var yyyy = d.getFullYear();
var date = dd + "/" + mm + "/" + yyyy;
var needSay = 'SUC';
var needSay2 = '-';
for(var i = 0; i < data.length; i++){
//row items
var values = data[i];
//column items
for(var j = 0; j < values.length; j++){
var row = values[j];
var checkRow = row;
//Logger.log(checkRow);
if(checkRow === needSay && checkRow === needSay2){
dataSheet.getRange(9 + i, 43).setValue(date);
};
};
};
}
Perhaps this is what you had in mind:
function sConfDate(){
var ss=SpreadsheetApp.getActive();
var dataSheet=ss.getSheetByName("Data");
var dataRange=dataSheet.getRange(9, 1, dataSheet.getLastRow()-8, 43);
var data=dataRange.getValues();
var datacol43=dataSheet.getRange(9,43,dataSheet.getLastRow()-8,1).getValues();
var date=Utilities.formatDate(new Date(), Session.getScriptTimeZone(), "dd/MM/yyyy");
data.forEach(function(r,i){
r.forEach(function(c,j){
if(c=='SUC' || c=='-') {
datacol43[i][0]=date;
}
});
});
dataSheet.getRange(9,43,dataSheet.getLastRow()-8,1).setValues(datacol43);
}
This might actually run faster:
function sConfDate(){
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName("Data");
var rg=sh.getRange(9, 1, sh.getLastRow()-8, 43);
var data=rg.getValues();
var crg=sh.getRange(9,43,sh.getLastRow()-8,1);
var cdata=crg.getValues();
var date=Utilities.formatDate(new Date(), Session.getScriptTimeZone(), "dd/MM/yyyy");
for(var i=0;i<data.length;i++) {
for(var j=0;j<data[i].length;j++) {
if(data[i][j]=='SUC' || data[i][j]=='-') {
cdata[i][0]=date;
break;
}
}
}
crg.setValues(cdata);
}
Perhaps this would be better.
function sConfDate2(){
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName("Data");
var rg=sh.getRange(9, 1, sh.getLastRow()-8, 8);
var data=rg.getValues();
var crg=sh.getRange(9,8,sh.getLastRow()-8,1);
var cdata=crg.getValues();
var date=Utilities.formatDate(new Date(), Session.getScriptTimeZone(), "dd/MM/yyyy");
for(var i=0;i<data.length;i++) {
var row=data[i];//Im guessing this is probably what you want unless you have particular columns in mind
if(row.indexOf('SUC')!=-1 && row.indexOf('-')!=-1) {
cdata[i][0]=date;
}
}
crg.setValues(cdata);
}
New to JavaScript objects. In the code below, I'm able to create and populate a list of book objects that each person has "checked out". However I am unable to "return" the books because I can't get seem to identify which patron's array the book is "checked out" in. I'm using
if (object in array) . . .
I got this from one of the previous answers. The statement block with the if never executes. Thanks for your help!
function Book(title, pub_date, call_number, authors){
this.title = title;
this.availability = true;
this.pub_date = pub_date;
this.current_date = null;
this.check_out_date = null;
this.call_number = call_number;
this.authors = authors;
}
Book.prototype.checkOut = function(){
this.availability = false;
var rdom = (Math.random() * 31 +1).toFixed(0);
var current_date = new Date();
this.check_out_date = new Date(current_date - rdom*24*3600*1000);
}
Book.prototype.checkIn = function(){
this.availability = true;
}
Book.prototype.isOverdue = function(){
var current_date = new Date();
if ((current_date - this.check_out_date)/1000/3600/24 > 14)
return true;
else
return false;
}
function Author(first_name, last_name){
this.first_name = first_name;
this.last_name = last_name;
}
function Patron(firstname, lastname, lib_card){
this.firstname = firstname;
this.lastname = lastname;
this.lib_card = lib_card;
this.books_out = [];
this.fine = 0;
}
Patron.prototype.readBook = function(book){
this.books_out.push(book);
}
Patron.prototype.returnBook = function(book){
this.books_out.pop(book);
}
var redAuthors, blueAuthors, greenAuthors, yellowAuthors, purpleAuthors
var redAuthor1 = new Author('John', 'Smith');
var redAuthor2 = new Author('James', 'Sullivan');
var redAuthors = [redAuthor1, redAuthor2];
var blueAuthors = greenAuthors = yellowAuthors = purpleAuthors = redAuthors;
redBook = new Book('Lakes', 1963, 456789, redAuthors);
blueBook = new Book('Rivers', 1964, 123456, blueAuthors);
greenBook = new Book('Streams', 1965, 234567, greenAuthors);
yellowBook = new Book('Ponds', 1966, 345678, yellowAuthors);
purpleBook = new Book('Brooks', 1967, 567891, purpleAuthors);
var catalog = [redBook, blueBook, greenBook, yellowBook, purpleBook]
var patron1 = new Patron('Sally', 'Hudson', '1');
var patron2 = new Patron('Rachel', 'Hung', '2');
var patron3 = new Patron('Andy', 'Cunningham', '3');
var patron4 = new Patron('Steve', 'Cote', '4');
var patron5 = new Patron ('Ted', 'Mitrou', '5');
var patrons = [patron1, patron2, patron3, patron4, patron5]
for (var day_count = 0; day_count < 10; day_count++){
for (var book_count = 0; book_count < 5; book_count++){
if (catalog[book_count].availability == true){
for (var pat_count = 0; pat_count < 5; pat_count++){
if (patrons[pat_count].books_out.length <= 1){
catalog[book_count].checkOut();
patrons[pat_count].readBook(catalog[book_count]);
break;
}
else
continue;
}
}
else {
catalog[book_count].checkIn();
for (pat_counter = 0; pat_counter < 5; pat_counter++){
if (catalog[book_count] in patrons[pat_counter].books_out){
if (catalog[book_count].isOverdue)
patrons[pat_counter].fine += 5;
patrons[pat_counter].books_out.returnBook(catalog[book_count]);
}
}
}
}
}
for (var k = 0; k < 5; k++){
console.log("Patron: " + patrons[k].firstname + " " + patrons[k].lastname);
console.log("Books checked out: ")
for (l = 0; l < patrons[k].books_out.length; l++) {
console.log(patrons[k].books_out[l].title);
}
console.log("Fine: $" + patrons[k].fine);
console.log();
}
You can use indexOf:
if (array.indexOf(object) > -1)
x in y would only return true if x is a string containing the name of a property on y.
Well, here is the json file http://herbalista.hol.es/group.json i am working with JSON.parse(); on Google apps script. I temporarily solve with this code by Choosing the post which have more than 15 likes, but i want to choose the one with more likes independently if have or not more than 15 likes.
function repost() {
var UsrAccess_token = "xxxxxxxxx"
var graph = "https://graph.facebook.com/xxxxxx/feed/?access_token="+UsrAccess_token+"";
var jsondata = UrlFetchApp.fetch(graph,{method:"get"}).getContentText();
var object = JSON.parse(jsondata);
var item = object.data;
var currentTime = new Date();
var year = currentTime.getUTCFullYear();
var month = (currentTime.getUTCMonth()) + 1;
var day = (currentTime.getUTCDate()) - 1;
if (day <= 9) {var day = "0"+day+"";}
if (month <= 9) {var month = "0"+month+"";}
var utime = ""+year+"-"+month+"-"+day+"T";
try {
var i = null;
for (i = 0; item.length > i; i += 1) {
var pubDate = item[i].created_time;
if (pubDate.match(utime)) { var likesdata = item[i].likes.data; var len = likesdata.length;
if (len > 15) {var popular = item[i].link;}}
}} catch(err) {
var err = "ERROR";
}
}
For this you can Choose a default value for a variable like var maxLikes = 0; and verify against len variable.
The code would be something like this:
function repost() {
var UsrAccess_token = "xxxxxxxxx"
var graph = "https://graph.facebook.com/xxxxxx/feed/?access_token="+UsrAccess_token+"";
var jsondata = UrlFetchApp.fetch(graph,{method:"get"}).getContentText();
var object = JSON.parse(jsondata);
var item = object.data;
var currentTime = new Date();
var year = currentTime.getUTCFullYear();
var month = (currentTime.getUTCMonth()) + 1;
var day = (currentTime.getUTCDate()) - 1;
if (day <= 9) {var day = "0"+day+"";}
if (month <= 9) {var month = "0"+month+"";}
var utime = ""+year+"-"+month+"-"+day+"T";
try {
var i = null;
var maxLikes = 0;
for (i = 0; item.length > i; i += 1) {
var pubDate = item[i].created_time;
if (pubDate.match(utime)) {
var likesdata = item[i].likes.data;
var len = likesdata.length;
if (len > maxLikes) {
maxLikes = len;
var popular = item[i].link;
}
}
}
} catch(err) {
var err = "ERROR";
}
}
Hope that helps!
In the following code i am trying to populate the javascript class,such that i get an object which i can stringify to json string.
function classValue(valuearrs) {
for (var i = 0; i < valuearrs.length; i++) {
for (j = 0; j < valuearrs[i].length; j++) {
this.id = valuearrs[i][j];
this.name = valuearrs[i][j];
this.somekey = valuearrs[i][j];
}
}
}
function CreatenestedarrObj( valuearr) {
this.Arrayparameters = [new classValue (valuearr)];
}
function ArrayMethodCall() {
var valuearr = new Array();
valuearr[0] = "myval1";
valuearr[1] = "myval2";
valuearr[2] = "myval3";
var valuearr1 = new Array();
valuearr1[0] = "myval11";
valuearr1[1] = "myval12";
valuearr1[2] = "myval13";
nestedarr = new Array();
nestedarr[0] = valuearr;
nestedarr[1] = valuearr1;
var x = new CreatenestedarrObj( nestedarr);
var strobject = JSON.stringify(x);
alert(strobject);
}
</script>
</head> <body> MethodCall: <input type="button" value="Call Method" onclick=" ArrayMethodCall ()" />
After Stringifying the value expected is {ArrayParameters:[{myval1,myval2,myval3},{myval1,myval12,myval13}]}.The thing i can think i am missing is creating new object each time in the loop but how ? or i might be totally wrong.Any help will be much appreciated.
try this
function classValue(valuearrs) {
var arr = []
for (var i = 0; i < valuearrs.length; i++) {
for (j = 0; j < valuearrs[i].length; j++) {
var temp = new Object();
temp.id = valuearrs[i][j];
temp.name = valuearrs[i][j];
temp.somekey = valuearrs[i][j];
arr[j] = temp;
}
}
return arr;
}
Change this:
function classValue(valuearrs) {
var arr=[]
for (var i = 0; i < valuearrs.length; i++) {
arr[i]={};
for (j = 0; j < valuearrs[i].length; j++) {
arr[i].id = valuearrs[i][j];
arr[i].name = valuearrs[i][j];
arr[i].somekey = valuearrs[i][j];
}
}
return arr;
}
i don't know why you need to split the nestedarr to id,name and somekey
but if you don't need to, just return the valuearrs and you will be fine:
function classValue(valuearrs) {
return valuearrs;
}
function CreatenestedarrObj( valuearr) {
this.Arrayparameters = [new classValue (valuearr)];
}
function ArrayMethodCall() {
var valuearr = new Array();
valuearr[0] = "myval1";
valuearr[1] = "myval2";
valuearr[2] = "myval3";
var valuearr1 = new Array();
valuearr1[0] = "myval11";
valuearr1[1] = "myval12";
valuearr1[2] = "myval13";
nestedarr = new Array();
nestedarr[0] = valuearr;
nestedarr[1] = valuearr1;
var x = new CreatenestedarrObj( nestedarr);
var strobject = JSON.stringify(x);
console.info(strobject);
}
the output is
{"Arrayparameters":[[["myval1","myval2","myval3"],["myval11","myval12","myval13"]]]}
or far better if you don't want it as Arrayparameters, you can use following code
var strobject = JSON.stringify(nestedarr);
and the output will be like this :
[["myval1","myval2","myval3"],["myval11","myval12","myval13"]]
I have found similar threads about this but I cant seem to make their solutions work for my specific issue. I currently have a calendar that will highlight the starting date of an Event. I need to change this to highlight the Start Date through the End Date.
Note: I did not write this code. It seems like whoever wrote this left a lot of junk in here. Please don't judge.
attachTocalendar : function(json, m, y) {
var arr = new Array();
if (json == undefined || !json.month || !json.year) {
return;
}
m = json.month;
y = json.year;
if (json.events == null) {
return;
}
if (json.total == 0) {
return;
}
var edvs = {};
var kds = new Array();
var offset = en4.ynevent.getDateOffset(m, y);
var tds = $$('.ynevent-cal-day');
var selected = new Array(), numberOfEvent = new Array();
for (var i = 0; i < json.total; ++i) {
var evt = json.events[i];
var s1 = evt.starttime.toTimestamp();
var s0 = s1;
var s2 = evt.endtime.toTimestamp();
var ds = new Date(s1);
var de = new Date(s2);
var id = ds.getDateCellId();
index = selected.indexOf(id);
if (index < 0)
{
numberOfEvent[selected.length] = 1;
selected.push(id);
}
else
{
numberOfEvent[index] = numberOfEvent[index] + 1;
}
}
for (var i = 0; i < selected.length; i++) {
var td = $(selected[i]);
if (td != null) {
if (!(td.hasClass("otherMonth"))){
td.set('title', numberOfEvent[i] + ' ' + en4.core.language.translate(numberOfEvent[i] > 1 ? 'events' : 'event'));
td.addClass('selected');
}
}
}
},
Instead of trying to select them all, I recommend you iterate over them instead. So something like this:
function highlightDates(startDate, endDate) {
var curDate = startDate;
var element;
$('.selected').removeClass('selected'); // reset selection
while (curDate <= endDate) {
element = getElementForDate(curDate)
element.addClass('selected');
curDate.setDate(curDate.getDate() + 1); // add one day
}
}
function getElementForDate(someDate) {
return $('#day-' + someDate.getYear() + "-" + someDate.getMonth() + "-" + someDate.getDay());
}