if variable equals else - javascript

Been trying all different ways of getting this to work. It's a Google spreadsheet script.
I get a error if a currency USDT comes up as there is no market BTC-USDT, it is USDT-BTC.
So I'm trying to make it set pair to altcoin+"-BTC" if the currency is USDT, Have tried multiple ways reading up different ways sometimes all I get it to do is USDT-BTC all the time, no other options.
This way I just get a error but it gives a better idea with what I'm trying to do.
for (var i = 1; i < currencyarray.length; i++) {
var altcoin = currencyarray[i][0];
{
if (altcoin = "USDT") {
var pair = altcoin+"-BTC";
else {
var pair = "BTC-"+altcoin;
}
//sheet.getRange((1+i), 3).setValue(pair);
//sheet.getRange((1+i), 4).setValue(currencyarray[i][1]);
sheet.getRange((1+i), 5).setValue(currencyarray[i][1]);
}
}
opps, sorry forgot extra =. Have changed it a little but when it gets to USDT it does BTC-BTC not USDT-BTC, Sorry I'm not a full time coder, try to teach myself.
for (var i = 1; i < currencyarray.length; i++) {
var altcoin = currencyarray[i][0];
{
if (altcoin == "USDT")
pair = altcoin+"-BTC";
else pair = "BTC-"+altcoin;
}
sheet.getRange((1+i), 5).setValue(currencyarray[i][1]);
var lastprice = bittrexGetlastprice(pair);
var value = (currencyarray[i][1]*lastprice);
sheet.getRange((1+i), 5).setValue(value);
}

In this line
if (altcoin = "USDT") {
You set altcoin to USDT, which counts as a truthy value, so the body of this if always runs. Use == when comparing
if (altcoin == "USDT") {

This works,
use == in if condition.

Related

Google apps script - Broken for loop

I'm working in Google apps script and seem to have screwed up one of my for loops. I'm sure that I am missing something trivial here, but I can't seem to spot it.
Code Snippet:
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheets = ss.getSheets();
var lastRow = sheets[3].getLastRow();
var zw = sheets[3].getRange(2, 1, lastRow - 1, 26).getValues();
for (var j = 0; j < zw.length; ++j) {
if (zw[j][9] === 'Yes') {
var masterEmail = [];
var firstLetterLastName = [];
var first2Letter = [];
var masterEmail.push(zw[j][22]);
var firstLetterLastName.push(zw[j][1].charAt(0).toLowerCase());
var first2Letter.push(zw[j][1].charAt(0).toLowerCase() + zw[j][1].charAt(1).toLowerCase());
//The rest of the function follows...
}
}
What's Not Working:
The for loop doesn't increment. When running the code in a debugger, var j stays at a value of 0.0, and the rest of the function only runs based of off the values in the 0 position of zw.
What I need it to do (AKA - How I thought I had written it:)
The ZW variable is holding a 2 dimensional array of cell values from a Google sheet. I'm looping through that, checking the 9th value of each array entry for a string of "Yes" and then running the rest of the function (for each column with a "Yes") if the condition is true.
I thought I had this working before, but recently had to restructure and optimize some things. Now I'm starting to think I may need to rethink things and use a different loop method. Can anyone educate me?
Edit: Here's a bit more context as requested:
function menuItem1() {
var ui = SpreadsheetApp.getUi();
var response = ui.alert('Are you sure you want to send emails?', ui.ButtonSet.YES_NO);
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheets = ss.getSheets();
var lastRow = sheets[3].getLastRow();
var zw = sheets[3].getRange(2, 1, lastRow - 1, 26).getValues();
if (response === ui.Button.YES) {
for (var j = 0; j < zw.length; j++) {
if (zw[j][9] === 'Yes') {
var firstLetterLastName = [];
firstLetterLastName.push(zw[j][1].charAt(0).toLowerCase());
//Other Stuff....
}
}
}
}
I have a menu item attached to a simple onOpen, that calls menuItem1(). Calling the function prompts the user with a warning that they are about to send emails, then goes about getting data to assign email addresses based on the contents of the sheets. firstLetterLastName is an example.
I'm still not getting the loop to function, is it because I have it between two if statements? (Here is a link to the sheet)
Indeed it is quite trivial. You have mixed up your increment. You wrote
for (var j = 0; j < zw.length; ++j)
which means that you do 1 + i (and we know that at the start i = 0 which means your value will always be 1) instead of using the usual
for (var j = 0; j < zw.length; j++)
which would mean that you do i + 1 and update i, so you will get the expected 0 + 1 1 + 1 etc
EDIT:
First, I recommend instead of something like
if (responseMir === ui.Button.YES) {
// Your For loop
doing
if (responseMir !== ui.Button.YES) {
return
}
and in a similar fashion in the for loop
if (zw[j][9] !== 'Yes') {
break
}
It mostly helps increase readability by not including large blocks of code under a single if, when all you want to do is to stop execution.
Your for loop gets broken because of the mistake here:
teacherEmailMir.push(selValsMir[j][7]);
So your loop will go over once. However on the next itteration, you try to push selValsMir[1][7] which does not exist. Note that each itteration you have var selValsMir = []; inside the loop, which means that for every j selValsMir will always be an empty array. So with the following line
selValsMir.push([zw[j][0], zw[j][1], zw[j][2], zw[j][3], zw[j][4], zw[j][5], zw[j][7], zw[j][22], zw[j][23], zw[j][24]]);
your array will always have selValsMir.lenght = 1 and selValsMir[0].length = 10. So obviously trying to access anything from selValsMir[1] will throw you an error and stop the script right there.
I also recommend looking over the if statements that look at the first and first 2 letters of the name as I believe you can accomplish the same with less code. Always try to streamline. Consider using switch() where you end up using a lot of else if

while (line = readline())

I'm new to JavaScript and are trying to solve a problem. I shall only write in JavaScript and the instructions are telling me to use readline(), for example like this: while (line = readline())
But I cant get how this works and I cant find any information about this in JavaScript. I want to get a users input and then put that in a variable. But when I try "while (line = readline())" I can's se anything happen (like with propt, which is the only way I know)...
Thankful for your help!
Here is my code (which works if I use alert and prompt istead of print and readline):
var usersNumber;
while (usersNumber = readline()) {
if (1 <= usersNumber && usersNumber <= 1000000000)
{
var inputBinary = usersNumber.toString(2);
var binaryArray = [];
for (i = 0; i < inputBinary.length; i++) {
binaryArray[i] = inputBinary.charAt(i);
};
binaryArray.reverse();
var stringBinaryFromArray = "";
for (i = 0; i < binaryArray.length; i++) {
stringBinaryFromArray = stringBinaryFromArray + binaryArray[i];
}
var digit = parseInt(stringBinaryFromArray, 2);
print(digit);
}
}
readline() is not a standard Javascipt function. You can use prompt() instead
while (usersNumber = prompt())
You might need to change the input from a string to a number.
while (usersNumber = Number(prompt()))
On another note, there are built-in functions you can use instead of the loops you have. split() and join(). You can even do it all in 1 line.
var stringBinaryFromArray = inputBinary.split('').reverse().join('');
(line = readline()) both assign line AND returns the value returned by readline()
if readline() returns null, line is null and the loop stops

Creating a new function that takes default arguments for another function (Javascript)

I am currently trying to create a defaultArguments function that takes in a function and some parameters that are set as default values. The steps I am thinking about taking to solve this particular problem is to:
Parse through the function in order to obtain what its arguments which could be anything.
Go through each argument that was extracted and replace arguments that have input parameters to its respective value.
Now, what I was thinking about doing next was to add additional default arguments into the input 'func'. I tried to:
Look up how to input a string as an argument into an existing function. However, the function then just reads the argument string as just a string.
Use the JavaScript .apply method. However, I won't always have all input values.
Here is the code I wrote so far.
function defaultArguments(func, params) {
var reg = /\(([\s\S]*?)\)/;
var extractVar = reg.exec(func);
if (extractVar) {
var arguments = extractVar[1].split(',');
}
for (i = 0; i < arguments.length; i++) {
if (params[arguments[i]]) {
arguments[i] = params[arguments[i]];
}
}
}
So for example, if I have a function
function add(a,b) { return a+b; };
I would use the defaultArguments function as such
var add_ = defaultArguments(add,{b:9});
console.log(add_(10) === 19); // b is defaulted to 9
console.log(add_(10,7) === 17); // b is given so use given value
console.log(add_()); // NaN
I would love some hints as to how to solve this problem and a different approach if I am approaching this problem incorrectly. I appreciate your time for reading this and I hope to see your response!
UPDATE:
So I was able to come up with a rough solution for this question. I was wondering if I approached the problem correctly and if there's any improvements do to my code. After researching a lot, I know that I shouldn't use eval(), but I don't know how else to tackle the problem. I am open to suggestions. Thanks in advance!
function defaultArguments(func, params) {
var stringed = func.toString();
var inputs = stringed.match(/\(.+\)/)[0].replace("(", "").replace(")", "").split(",")
for (i = 0; i < inputs.length; i++) {
inputs[i] = ""+inputs[i]+" = "+inputs[i]+" || "+params[inputs[i]]+";"
}
for (i = 0; i < inputs.length; i ++) {
stringed = stringed.replace("{", "{ "+inputs[i]+"")
}
var newFunc = "var restoreFunc = " + stringed;
eval(newFunc);
return restoreFunc;
}

Javascript if value is in array else in next array

I have found a few posts on here with similar questions but not entirely the same as what I am trying. I am currently using a simple if statement that checks the data the user enters then checks to see if it starts with a number of different values. I am doing this with the following:
var value = string;
var value = value.toLowerCase();
country = "NONE";
county = "NONE";
if (value.indexOf('ba1 ') == 0 || value.indexOf('ba2 ') == 0 || value.indexOf('ba3 ') == 0) { //CHECK AVON (MAINLAND UK) UK.AVON
country = "UK";
county = "UK.AVON";
} else if(value.indexOf('lu') == 0){//CHECK BEDFORDSHIRE (MAINLAND UK) UK.BEDS
country = "UK";
county = "UK.BEDS";
}
I have about 20-30 different if, else statements that are basically checking the post code entered and finding the county associated. However some of these if statements are incredibly long so I would like to store the values inside an array and then in the if statement simply check value.indexOf() for each of the array values.
So in the above example I would have an array as follows for the statement:
var avon = new Array('ba1 ','ba 2','ba3 ');
then inside the indexOf() use each value
Would this be possible with minimal script or am I going to need to make a function for this to work? I am ideally wanting to keep the array inside the if statement instead of querying for each array value.
You can use the some Array method (though you might need to shim it for legacy environments):
var value = string.toLowerCase(),
country = "NONE",
county = "NONE";
if (['ba1 ','ba 2','ba3 '].some(function(str) {
return value.slice(0, str.length) === str;
})) {
country = "UK";
county = "UK.AVON";
}
(using a more performant How to check if a string "StartsWith" another string? implementation also)
For an even shorter condition, you might also resort to regex (anchor and alternation):
if (/^ba(1 | 2|3 )/i.test(string)) { … }
No, it doesn’t exist, but you can make a function to do just that:
function containsAny(string, substrings) {
for(var i = 0; i < substrings.length; i++) {
if(string.indexOf(substrings[i]) !== -1) {
return true;
}
}
return false;
}
Alternatively, there’s a regular expression:
/ba[123] /.test(value)
My recomendation is to rethink your approach and use regular expressions instead of indexOf.
But if you really need it, you can use the following method:
function checkStart(value, acceptableStarts){
for (var i=0; i<acceptableStarts.length; i++) {
if (value.indexOf(acceptableStarts[i]) == 0) {
return true;
}
}
return false;
}
Your previous usage turns into:
if (checkStart(value, ['ba1', ba2 ', 'ba3'])) {
country = 'UK';
}
Even better you can generalize stuff, like this:
var countryPrefixes = {
'UK' : ['ba1','ba2 ', 'ba3'],
'FR' : ['fa2','fa2']
}
for (var key in countryPrefixes) {
if (checkStart(value, countryPrefixes[key]) {
country = key;
}
}
I'd forget using hard-coded logic for this, and just use data:
var countyMapping = {
'BA1': 'UK.AVON',
'BA2': 'UK.AVON',
'BA3': 'UK.AVON',
'LU': 'UK.BEDS',
...
};
Take successive characters off the right hand side of the postcode and do a trivial lookup in the table until you get a match. Four or so lines of code ought to do it:
function getCounty(str) {
while (str.length) {
var res = countyMapping[str];
if (res !== undefined) return res;
str = str.slice(0, -1);
}
}
I'd suggest normalising your strings first to ensure that the space between the two halves of the postcode is present and in the right place.
For extra bonus points, get the table out of a database so you don't have to modify your code when Scotland gets thrown out of leaves the UK ;-)

How can i know its valid in JS?

I am developing an Adobe interactive form with LiveCycle LC designer with JavaScript.
// Identify required fields (it may be a free text field, drop-down, check box, i mean there 3 kinds possibilties) and make yellow colored them
var myArrayYellow = new Array();
var yellowFields;
yellowFields = my_required_fields_list_string.rawValue
myArrayYellow = yellowFields.split(" ");
for (var i = 0; i < myArrayYellow.length; i++) {
===> Here at this point, i want to check the existence of [i] field in the form that its a valid field/objetc or not? bcz, i have chances of getting non-existing fields in the my_required_fields_list_string, hence prior to assigning yellow color to them, i want to check their validity on the form or not? Pls. let me know the JS for this // if its true/found, then only assign yellow color as below
xfa.resolveNode("MY_ADOBE_FORM.." + myArrayYellow [i]).ui.oneOfChild.border.fill.color.value = "255,255,254"
};
For some other purpose, some expert gave me a JS as below, i tried to tune it as per my above requirement, but its not working
function findNodes(vNode){
if (vNode.className === "field"){
if (vNode.isPropertySpecified("name") === true){
var myStateName = new RegExp(vNode.name);
var returnValue = GFL.search(myStateName);
if (returnValue != -1) {
this.ui.oneOfChild.border.fill.color.value = "192,192,192";
this.access = "readOnly";
} else {
this.ui.oneOfChild.border.fill.color.value = "255,255,255"; //whatever colour is open access
this.access = "open";
}
}
}
for (var a=0;a<vNode.nodes.length;a++) {
findNodes(vNode.nodes.item(a));
}
}
findNodes(xfa.form);
if I understand your problem, you need to check if xfa.resolveNode returns something and handle it from there.
var node;
if ( (node=xfa.resolveNode("MY_ADOBE_FORM.." + myArrayYellow[i]) )!==null){
node.ui.oneOfChild.border.fill.color.value = "255,255,254"
}
If I understand correctly, you are trying to check if all of your values in the array are valid before preforming operations on them. Just check and make sure they are not null.
EDIT: You should probably check for empty string as well.
for (var i = 0; i < myArrayYellow.length; i++) {
if (!(myArrayYellow[i] == null || myArrayYellow[i] == "")){
//Do Stuff
}
}

Categories