Google Script call another function to return a value - google-apps-script

I'm getting to grips with beginner methods of GScript now but so far have only used one function. Could someone show me how to 'call' another function to check for something and then return a TRUE or FALSE. Here is my attempt (it will eventually check a lot of things but I'm just checking one thing to start..)
Function callAnotherFunctionAndGetResult () {
MyResult = call(CheckTrueFalse)
if(MyResult = True then.. do something)
};
function CheckTrueFalse() {
if(3 > 2) {
CheckTrueFalse = TRUE
Else
CheckTrueFalse = FALSE
};
So basically I just want to get the other function to check something (in this case is 3 bigger than 2?) if it is then return TRUE. From this I should have the knowledge to modify for the real purpose. I'm used to Visual Basic so I've written it more how that would look - I know that won't work. Could someone help me convert so will work with Google Script please?

A function with a return statement is what you're looking for. Assuming you need the called function to take some input from the main function:
function mainFunction() {
//...
var that = "some variable found above";
//call other function with input and store result
var result = otherFunction(that);
if (result) {
//if result is true, do stuff
}
else {
//if result is false, do other stuff
}
}
function otherFunction(that) {
var this = "Something"; //check variable
return (this == that);
//(this == that) can be any conditional that evaluates to either true or false,
//The result then gets returned to the first function
}
You could also skip assigning the result variable and just check the returned condition directly, i.e.:
if (otherFunction(that)) {
//do stuff
}
else {do other stuff}
Let me know if you need me to clarify any of the syntax or if you have any more questions.

Here's a basic sample that might help you:
function petType(myPet){
return myPet;
}
function mainFunctoin(){
var newPet = petType("dog");
if(newPet === "dog"){
Logger.log("true");
}else{
Logger.log("false");
}
}
Execute mainFunction().
If you set petType to "cat", it will return false; but, if you set it to "dog", it will return true.
Let me know if it helped.

Related

Trouble with method that takes in a function and its arguments

I am having trouble passing a kata. I believe I am on the right track, but do not fully understand how to retrieve the desired results.
The Instructions
Write a method that takes in a function and the arguments to the function and returns another function which when invoked, returns the result of the original function invoked with the supplied arguments.
Example Given
Given a function add
function add (a, b) {
return a + b;
}
One could make it lazy as:
var lazy_value = make_lazy(add, 2, 3);
The expression does not get evaluated at the moment, but only when you invoke lazy_value as:
lazy_value() => 5
Here is my half a day endeavor conclusion
var make_lazy = function () {
var innerFunction = null;
var array = [];
for (var i = 0; i < arguments.length; i++) {
if (typeof arguments[i] == 'function') {
innerFunction = arguments[i];
} else {
array.push(arguments[i]);
}
}
innerFunction.apply(innerFunction, array);
innerFunction();
};
I'm using arguments and apply() and think I am close? However I am getting TypeError: lazy_sum is not a function at Object.exports.runInThisContext within test results. Any help, especially understanding what is going on, is appreciated. Thanks
...
return function() {
return innerFunction.apply(this, array);
};
};
Thanks again all. Problem solved.

nightwatch.js return value from function outside a test

I have trouble moving certain code outside a test into a function that needs to return a value.
Here is part of my code for the test file
function getCountOfTopics(browser){
var count;
browser.getText('#sumTopics',
function(result){
count = result.value;
console.log(result.value);
}
);
return count;
};
module.exports = {
'Create article' : function(browser){
var noOfThreadsByInlineCode, noOfThreadsByFunction;
browser.getText('#sumTopics',
function(result){
noOfThreadsByInlineCode = result.value;
}
);
noOfThreadsByFunction = getCountOfTopics(browser);
browser.end();
}
}
Now, the variable noOfThreadsByInlineCode indeed gets the value in the DOM, but the variable noOfThreadsByFunction is undefined. The console does indeed print the correct value, so the function does get the correct value out of the DOM.
I would appreciate help in updating the function so that I do get the value returned.
One word answer is Asynchronisity. The code doesn't wait for your callback to get complete, thats what the feature of Node JS is.
If you are in desperately in need for the content inside of the callback you can write this variable into a file and then access it anywhere you want inside your code. Here's a bit of a workaround:
Save something in a file:
var fs = require('fs');
iThrowACallBack(function(response){
fs.writeFile('youCanSaveData.txt', this.response, function(err) {
if (err) throw err;
console.log('Saved!');
browser.pause(5000);
});
});
Access it somewhere else:
iAccessThefile(){
response = fs.readFileSync('youCanSaveData.txt').toString('utf-8');
}
Hope it helps.
You return variable 'count' outside the callback,that is why.You can take a look this topic How to return value from an asynchronous callback function?
function getCountOfTopics(browser){
var count;
browser.getText('#sumTopics',
function(result){
count = result.value;
console.log(result.value);
/// result.value is available in this callback.
}
);
What do you want to do with the 'value'?
ps:do not remember custom_command.I think it is very helpful for this issue.

Call a random function from an array

I have three functions that I have listed in an array. Now I need a random function of the three to be called when pressing a button. However, when I press the button it calls all three functions and I'm not quite sure where I've gone wrong. It looks like this right now:
function Arm1function1(){
this.parent.parent.parent.Armfront1.visible = true;
this.parent.parent.parent.Armback1.visible = false;
}
function Arm1function2(){
this.parent.parent.parent.Armfront1.visible = false;
this.parent.parent.parent.Armback1.visible = true;
}
function Arm1function3(){
this.parent.parent.parent.Armfront1.visible = false;
this.parent.parent.parent.Armback1.visible = false;
}
function getRandomElementOf(Armbuttonarray1:Array):Object {
var Armbuttonarray1:Array = [Arm1function1(), Arm1function2(), Arm1function3()];
var idx:int=Math.floor(Math.random() * Armbuttonarray1.length);
return Armbuttonarray1[idx];
}
Randombutton1part1.addEventListener(MouseEvent.CLICK, Randombutton1part1Click);
function Randombutton1part1Click(e:MouseEvent):void
{
getRandomElementOf(null);
}
Any clue of where I've gone wrong?
Your issue is this line:
var Armbuttonarray1:Array = [Arm1function1(), Arm1function2(), Arm1function3()];
When populating that array, you are actually populating it with the results of the functions.
Should be:
var Armbuttonarray1:Array = [Arm1function1, Arm1function2, Arm1function3];
Notice the lack of parenthesis ().
You want to actually execute the function on the click handler, so you'll need to tweak that a bit too:
getRandomElementOf(null)();
or
getRandomElementOf(null).call();
As an aside, your getRandomElementOf function should probably look more like this:
function getRandomElementOf(array:Array):Object {
return array[Math.floor(Math.random() * array.length)];
}
Then do:
getRandomElementOf([Arm1function1, Arm1function2, Arm1function3])();

Custom binding to return the last Json record

I'm using the following code to load all Json data.
$.getJSON("/Home/GetSortedLists", function (allData) {
var mappedSortedLists = $.map(allData, function (item) { return new SortedLists(item) });
viewModel.sortedlists(mappedSortedLists);
});
I also need to load a single record from the same Json data; the record with the highest SortedListsID value (i.e. the last record entered).
Can anybody suggest the best way to do this? I've considered adding viewModel.lastsortedlist and amending the above code somehow. I've also considered creating a last custom binding to do something like:
<tbody data-bind="last: sortedlists.SortedListID">
All advice welcome.
Unless you want to do more ui-related stuff with the record, I don't think you need the custom binding.
It should be enough to compute it in the getJSON callback and save it in the viewModel:
$.getJSON("/Home/GetSortedLists", function (allData) {
var mappedSortedLists = $.map(allData, function (item) { return new SortedLists(item) });
viewModel.sortedlists(mappedSortedLists);
//correct the sort function if it's bad, or drop it if allData is already sorted
var sortedData = allData.sort(function(a,b){ return a.SortedListID - b.SortedListID})
viewModel.lastSortedList(sortedData[sortedData.length - 1])
});
Or, if it can change outside the getJSON callback, you could also make it a computed observable:
viewModel.lastSortedList = ko.computed(function(){
//correct the sort function if it's bad, or drop it
var sortedData = mappedSortedLists().sort(function(a,b){ return a.SortedListID - b.SortedListID})
return sortedData[sortedData.length - 1]
}, this)

Call two function in one onchange = not working

I have been searching how to put more than one function in onchange and I found how something like this for example: onchange = "function1(); function2();".
My problem here is I have followed what does the example like, but only function1 is working, function2 is not working. If I make it otherwise to onchange = "function2(); function1();", only function2 is working, function1 is not working, the same.
Any ideas guys?
Thanks.
The functions, I used Ajax:
function1(test)
{
var kode = test.value;
if (!kode) return;
xmlhttp.open('get', '../template/get_name-opr.php?kode='+kode, true);
xmlhttp.onreadystatechange = function() {
if ((xmlhttp.readyState == 4) && (xmlhttp.status == 200))
{
//alert(kode);
document.getElementById("code").innerHTML = xmlhttp.responseText;
}
return false;
}
xmlhttp.send(null);
}
function2(test)
{
var kode = test.value;
if (!kode) return;
xmlhttp**1**.open('get', '../template/get_name2-opr.php?kode='+kode, true);
xmlhttp**1**.onreadystatechange = function() {
if ((xmlhttp**1**.readyState == 4) && (xmlhttp**1**.status == 200))
{
//alert(kode);
document.getElementById("code2").innerHTML = xmlhttp**1**.responseText;
}
return false;
}
xmlhttp**1**.send(null);
}
To solve my problem, I created two xmlhttp different. (xmlhttp and xmlhttp1).
Go through the link I gave, it seems to be problem with the way you are managing the xmlhttprequest objects, manage their instances properly, in your case because you are using the same xmlhttprequest for two simultaneous AJAX requests, only one of them is getting served. Either wait for one of them to get served or create two instances of the xmlhttprequest.
The statement xmlhttp.readystate = function() {...} obviously replaces the readystate property of that xmlhttprequest object, so on your second function, that is being replaced( because you are using the xmlhttprequest for both of them ). This is why you are seeing the funny behaviour.
Call function2() at the end of function1().
onchange = "function1()"
function1(){
...
function1 body;
...
function2()
}
Wrap the two function calls in one and call that function!
function myFirstFunction() {
//body
}
function mySecondFunction() {
//body
}
//Call this guy.
function myWrappedFunction() {
myFirstFunction();
mySecondFunction();
}