String comparison not as expected - javascript

I have written the following code looking for a string token in an array.
var parseCSVLines = function(lines) {
var valueObj = {};
var delim = ',';
var isLayer = false;
var isGroup = false;
for(var i = 0; i < lines.length; i++){
//skips CR/CF lines
if(!lines[i]) continue;
//only data lines reach this loop
var data = lines[i].split(delim);
/*********looks for tag*************/
if(data[0] == '#L' || data[0] == '#l'){
//on occasions, data[0] is '#L' or '#G' still execution reaches here
isLayer = true;
}else if(data[0] == '#G' || data[0] == '#g'){
isGroup = true;
}else{
if(isLayer){
valueObj[data[0]] = {
layerInfo: data[1] == 'on' ? true : false
};
}
else if(isGroup){
valueObj[data[0]] = {
GroupInfo: data[1] == 'on' ? true : false
};
}
}
}
return valueObj;
};
I loop through lines and mark next line to get data. Weirdly when data[0] is '#L' and '#G', first if statement is executed. What have I done wrong?

The if statement is fine, even if you have data[0]='#G#L'...it will never go into data[0]=='#L'||data[0]=='#l'
On my mind you are stuck in the logic-
if (data[0] == '#L' || data[0] == '#l') {
isLayer = true;
//isGroup=false; you should toggle isGroup
} else if (data[0] == '#G' || data[0] == '#g') {
isGroup = true;
//isLayer=false; you should toggle isLayer
} else { //do you want else here??? This would pick the value of isLayer or isGroup according to previous line processed but not the value according to current line being processed.
if (isLayer) {
valueObj[data[0]] = {
layerInfo: data[1] == 'on' ? true : false
};
} else if (isGroup) {
valueObj[data[0]] = {
GroupInfo: data[1] == 'on' ? true : false
};
}
}
Example:
line1: '#L,hi'
line2:'#G,hi'
line3:'hi'
processing first line will set isLayer=true;
processing second line will set isGroup=true;//remember isLayer is still true - you haven't set it to false;
processing third line will trigger your else part...and get into first condition where if(isLayer) will be true
To make it work:
//update isLayer and isGroup for every iteration to keep the logic inline
isLayer=(data[0] == '#L' || data[0] == '#l');
isGroup=(data[0] == '#G' || data[0] == '#g');
if(!isLayer && !isGroup) {
if (isLayer) {
valueObj[data[0]] = {
layerInfo: data[1] == 'on' ? true : false
};
} else if (isGroup) {
valueObj[data[0]] = {
GroupInfo: data[1] == 'on' ? true : false
};
}
}

Try this:
if(data[0] == "#l" || data[0] == "#L") {
if(data[0].search("#g") != -1 || data[0].search("#G") != -1){
}else{
isLayer = true;
}
}else if(data[0] == "#g" || data[0] == "#G"){
if(data[0].search("#l") != 0 || data[0].search("#L") != 0){
}else{
is group = true;
}
}
You see, what you weren't doing was checking if both were present. What my code does is checks that
The item is #g or #l
The item is not the opposite as well.
This ensures that one, and only one option is chosen.
Good day, And good luck.

Related

What is the best way to deal with multiple else if statements to increase speed in Google Apps Script?

I have a function that is supposed to unhide certain columns, but only if other filters that relate to the columns are not in use. Because there are 4 other filters that it needs to check to see if they are in use (either 'true' or 'false'), there are 16 possibilities that the function needs to run through.
I've used else if statements to accomplish this and it does work, but it is incredibly slow. I was wondering if there is a more appropriate way to deal with all the possible options that is faster.
This is the code I currently have (sorry if I've shown too much, not sure how much I need to include):
function Unfilter(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var numCols = sheet.getRange(1,3).getValue(); //gets the number of columns to loop through
var xRow = sheet.getRange(1,5).getValue() + 16; //gets the target row to run the blank check on
// check filter statuses
var nameShow = sheet.getRange(1,1).getValue();
var statusShow = sheet.getRange(2,1).getValue();
var dateShow = sheet.getRange(3,1).getValue();
var evidenceShow = sheet.getRange(4,1).getValue();
//loop through all target columns and unhide all columns that are not filtered
for (var i=10; i<=numCols; i++) {
if (sheet.getRange(xRow,i).getValue() == "") {
var catType = sheet.getRange(16,i).getValue();
if (nameShow == true && statusShow == true && dateShow == true && evidenceShow == true) {
sheet.showColumns(i)
} else if (nameShow == false && statusShow == true && dateShow == true && evidenceShow == true) {
if(catType !== "Name") {
sheet.showColumns(i);
}
} else if (nameShow == false && statusShow == false && dateShow == true && evidenceShow == true){
if (catType == "Date" || catType == "Evidence") {
sheet.showColumns(i);
}
} else if (nameShow == false && statusShow == true && dateShow == false && evidenceShow == true) {
if (catType == "Status" || catType == "Evidence") {
sheet.showColumns(i);
}
} else if (nameShow == false && statusShow == true && dateShow == true & evidenceShow == false){
if (catType == "Status"|| catType == "Date") {
sheet.showColumns(i);
}
} else if (nameShow == false && statusShow == false && dateShow == false && evidenceShow == true){
if (catType == "Evidence") {
sheet.showColumns(i);
}
} else if (nameShow == false && statusShow == false && dateShow == true && evidenceShow == false){
if (catType == "Date") {
sheet.showColumns(i);
}
}
//...etc for all 9 remaining possibilities
}
}
}
Even if you can't speed up showColumns() function you can significantly accelerate your script if you will use getValue() or getValues() as few as it possible. For example here you invoke these functions more than 7 times on the same sheet with static data. It's far from best practices:
You could use getValues() just once to get all data from the sheet and analyze the array instead. It would be much faster. getValue() / getValues() are quite slow and intentionally limited functions.
For example:
var data = sheet.getRange(1,1,10,10).getValues(); // get the array
var numCols = data[0][2];
var xRow = data[0][4] + 16;
var nameShow = data[0][0];
var statusShow = data[1][0];
var dateShow = data[2][0];
var evidenceShow = data[3][0];
// etc
I think it will be about five seconds faster already.
And it will even more faster if you change getRange(xRow,i).getValue() to data[xRow-1][i-1] in the loop.

Getting an Unknown CORS error in Odoo-12 POS UI Book Orders

I am getting this error on POS UI I really need help because I don't understand the error
I am using the Book Order module and I often get this error like 1 in 10 book orders
Uncaught SyntaxError: Unexpected token u in JSON at position 0
at JSON.parse (<anonymous>)
at child.add_product (point_of_sale.assets.js:493)
at Class.line_select (point_of_sale.assets.js:429)
at HTMLButtonElement.<anonymous> (point_of_sale.assets.js:425)
at HTMLTableSectionElement.dispatch (web.assets_common.js:892)
at HTMLTableSectionElement.elemData.handle (web.assets_common.js:865)
here's how I modified the add_product function
add_product: function(product, options){
var can_add = true;
var changes = this.pos.get_order();
var self = this;
if(changes.selected_orderline){
if(changes.selected_orderline.order){
if(changes.selected_orderline.order.quotation_ref){
if(changes.selected_orderline.order.quotation_ref.book_order){
can_add= false;
}
}
}
}
if (can_add){
if(this._printed){
this.destroy();
return this.pos.get_order().add_product(product, options);
}
this.assert_editable();
options = options || {};
var attr = JSON.parse(JSON.stringify(product));
attr.pos = this.pos;
attr.order = this;
var line = new POSInheritmodel.Orderline({}, {pos: this.pos, order: this, product: product});
if(options.quantity !== undefined){
line.set_quantity(options.quantity);
}
if(options.price !== undefined){
line.set_unit_price(options.price);
}
//To substract from the unit price the included taxes mapped by the fiscal position
this.fix_tax_included_price(line);
if(options.discount !== undefined){
line.set_discount(options.discount);
}
if(options.discounted_amount !== undefined){
line.set_discount_amount(options.discounted_amount);
}
if(options.discount_percentage !== undefined){
line.set_if_discount_percentage(options.discount_percentage);
}
if(options.discount_amount !== undefined){
line.set_if_discount_amount(options.discount_amount);
}
if(options.extras !== undefined){
for (var prop in options.extras) {
line[prop] = options.extras[prop];
}
}
if(options.uom !== undefined || options.uom !== false){
line.set_unit_id(options.uom);
}
if(options.is_board_feet !== undefined && options.is_board_feet){
line.set_is_board_feet(true);
line.set_length(product.length);
line.set_thickness(product.thickness);
line.set_width(product.width);
// console.log(product.length);
}else if(options.is_board_feet !== undefined && !options.is_board_feet){
line.set_is_board_feet(false);
}else{
if(changes.attributes.client !== null){
if(changes.attributes.client.is_wholesale || changes.attributes.client.is_retail){
if(product.is_board_feet){
line.set_is_board_feet(true);
line.set_length(product.length);
line.set_thickness(product.thickness);
line.set_width(product.width);
}
}
}
}
if(options.is_lineal_feet && options.is_lineal_feet !== undefined){
line.set_is_lineal_feet(true);
line.set_length(product.length);
// console.log(product.length);
}else if(options.is_lineal_feet !== undefined && !options.is_lineal_feet){
line.set_is_lineal_feet(false);
}else{
if(changes.attributes.client !== null){
if(changes.attributes.client.is_wholesale || changes.attributes.client.is_retail){
if(product.is_lineal_feet){
line.set_is_lineal_feet(true);
line.set_length(product.length);
}
}
}
}
if(options.is_lineal_meter && options.is_lineal_meter !== undefined){
line.set_is_lineal_meter(true);
line.set_length(product.length);
// console.log(product.length);
}else if(options.is_lineal_meter !== undefined && !options.is_lineal_meter){
line.set_is_lineal_meter(false);
}else{
if(changes.attributes.client !== null){
if(changes.attributes.client.is_wholesale || changes.attributes.client.is_retail){
if(product.is_lineal_meter){
line.set_is_lineal_meter(true);
line.set_length(product.length);
}
}
}
}
if(options.with_base_price){
line.set_with_base_price(true);
if(options.base_price_discount !== undefined){
line.set_base_price_discount(options.base_price_discount);
}
if(options.markup !== undefined){
line.set_markup(options.markup);
}
// console.log(product.length);
}
if(options.is_weight !== undefined && options.is_weight){
line.set_is_weight(true);
line.set_weight_receipt_display(options.base_weight);
}else if(options.is_weight !== undefined && !options.is_weight){
line.set_is_weight(false);
if(options.base_weight !== undefined && options.base_weight != 0){
line.set_weight_receipt_display(options.base_weight);
}else{
line.set_weight_receipt_display(product.weight);
}
}else{
if(options.base_weight !== undefined && options.base_weight != 0){
line.set_weight_receipt_display(options.base_weight);
}else{
line.set_weight_receipt_display(product.weight);
}
if(changes.attributes.client !== null){
if(changes.attributes.client.is_wholesale || changes.attributes.client.is_retail){
if(product.is_weight){
line.set_is_weight(true);
}
}
}
}
var to_merge_orderline;
for (var i = 0; i < this.orderlines.length; i++) {
if(this.orderlines.at(i).can_be_merged_with(line) && options.merge !== false){
to_merge_orderline = this.orderlines.at(i);
}
}
if (to_merge_orderline){
to_merge_orderline.merge(line);
} else {
this.orderlines.add(line);
}
this.select_orderline(this.get_last_orderline());
if(line.has_product_lot){
this.display_lot_popup();
}
}else{
self.pos.gui.show_popup('error',{
title :_t('Modification Restricted'),
body :_t('Modification is not allowed for booked orders.'),
});
}
},
this is all that I can give I didn't try anything to fix this because I don't really know where to start any help is very much appreciated thank you.

if statements being skipped even when both expressions are true

I have a webpage that populates a table with arrays. It has a doClick function so that when a user clicks on a cell it passes the row and column of the cell to the function. Example cell: onclick="doClick(0,1)"
function doClick(row, col)
{
var top = row -1;
var bottom = row +1;
var left = col -1;
var right = col +1;
var swapped = false;
if ((top != -1) && (cells[top][col].innerHTML = ""))
{
cells[top][col].innerHTML = cells[row][col].innerHTML;
cells[row][col].innerHTML = "";
swapped = true;
}
else if ((right != 4) && (cells[row][right].innerHTML = ""))
{
cells[row][right].innerHTML = cells[row][col].innerHTML ;
cells[row][col].innerHTML = "";
swapped = true;
}
else if ((bottom != 4) && (cells[bottom][col].innerHTML = ""))
{
cells[bottom][col].innerHTML = cells[row][col].innerHTML;
cells[row][col].innerHTML = "";
swapped = true;
}
else if ((left != -1) && (cells[row][left].inn = ""))
{
cells[row][lef].innerHTML = cells[row][col].innerHTML;
cells[row][col].innerHTML = "";
swapped = true;
}
else
{
alert("Illegal Move.");
}
. The problem is, even if both if expressions are true, the if statement is being skipped and it's falling through to the else statement. I've desk checked it and run it through the developer tools and checked values. A statement that was true on both expressions was skipped. Any suggestions?
cells[row][right].innerHTML = ""
is wrong. You are missing the double (triple) =.
The correct way should be...
cells[row][right].innerHTML === ""
It looks like maybe there are a few typos or misconceptions in your code.
A quick note about Conditions in an IF statement
A statement like (cells[top][col].innerHTML = "") as a condition will always return true as this is setting cells[top][col].innerHTML as "" or at least instantiating the variable. So, the proper condition to test absolutely true or false would be (cells[top][col].innerHTML === ""). However, you can get away with not even doing that and simply replace (cells[top][col].innerHTML = "") with cells[top][col].innerHTML. You may run into some other issues though is the variable is not instantiated already, either way. I would wrap the latter logic in an IF statement to check if cells[top][col].innerHTML is even instantiated.
To fix this, check out the following modifications I have made to your code.
function doClick(row, col)
{
var top = row -1;
var bottom = row +1;
var left = col -1;
var right = col +1;
var swapped = false;
if(typeof cells[top][col].innerHTML !== 'undefined' $$ cells[top][col].innerHTML !== null)
{
if ((top != -1) && cells[top][col].innerHTML !== '')
{
cells[top][col].innerHTML = cells[row][col].innerHTML;
cells[row][col].innerHTML = "";
swapped = true;
}
else if ((right != 4) && cells[row][right].innerHTML !== '')
{
cells[row][right].innerHTML = cells[row][col].innerHTML ;
cells[row][col].innerHTML = "";
swapped = true;
}
else if ((bottom != 4) && (cells[bottom][col].innerHTML))
{
cells[bottom][col].innerHTML = cells[row][col].innerHTML;
cells[row][col].innerHTML = "";
swapped = true;
}
else
{
alert("Illegal Move.");
}
}
else if (typeof cells[row][left].inn !== 'undefined' && (left != -1) && cells[row][left].inn !== '')
{
cells[row][lef].innerHTML = cells[row][col].innerHTML;
cells[row][col].innerHTML = "";
swapped = true;
}
else
{
alert("Illegal Move.");
}
}
An example working to demonstrate the above code
var testVar1 = '';
var testVar2 = 'Hello';
// var testVar3; <- Left this un-instantiated to test existance
// Testing if a var is empty but exists
if(typeof testVar1 !== 'undefined' && testVar1 !== null){
if(testVar1 !== ''){
alert('testVar1 has a value!');
}{
alert('testVar1 does not have a value!');
}
}
// Testing if a var is empty but exists
if(typeof testVar2 !== 'undefined' && testVar2 !== null){
if(testVar2 !== ''){
if(testVar2 === 'Hello'){
alert('testVar2 has a value! Value: ' + testVar2);
}{
alert('testVar2 has a value but it is not the one we expected.');
}
}{
alert('testVar2 does not have a value!');
}
}
// Test existance
if(typeof testVar3 !== 'undefined' && testVar3 !== null){
alert('testVar3 exists!');
}else{
alert('testVar3 does not exist!');
}

my code could not able to detect undefined and null values can someone please correct it?

var isTopper = false
var marksobtained = window.prompt('please enter the marks obtained ')
if (marksobtained == undefined || marksobtained == null || marksobtained == '') {
alert('invalid')
} else if (marksobtained < 0 || marksobtained > 100) {
alert('enter between 0 to 100')
} else {
marksobtained = Number(marksobtained)
var totalmarks = 100
var percentage = (marksobtained / totalmarks) * 100
if (percentage > 90) {
isTopper = true
} else {
isTopper = false
}
alert(isTopper)
}
I don't why your code is not working for you(as it is working for us), I just made few modifications in your code like replace if (marksobtained == undefined || marksobtained == null || marksobtained == '') this with this if (!marksobtained) and
As you are asking only one subject marks you don't have to calculate percentage you can directly tell on the basis of marks whether he/she is topper or not(I am saying this only because you are asking only one subject marks and that marks is in between 1 to 100)
var isTopper = false
var marksobtained = window.prompt('please enter the marks obtained ')
if (!marksobtained || isNaN(marksobtained)) {
alert('invalid')
} else if (marksobtained < 0 || marksobtained > 100) {
alert('enter between 0 to 100')
} else {
marksobtained = Number(marksobtained);
if (marksobtained > 90) {
isTopper = true
} else {
isTopper = false
}
alert(isTopper)
}
I dont know where is your problem. Please provide some details. alert('invalid') is working correctly and being called when value is empty string.
Instead of
if (marksobtained == undefined || marksobtained == null || marksobtained == '')
You can simply use
if (!marksobtained) { ...

jQuery check if two values is blank

I have three values:
var tbb = $("#total1 span").text();
var tmb = $("#total2 span").text();
var tab = $("#total3 span").text();
Each of them could be blank.
What is the better way in javascript/jquery check if two of these values is blank?
UPDATE
here is what i mean, my a bit ugly and a "lot of lines" solution
var i = 0;
if (tab != "") {
i++;
}
if (tmb != "") {
i++;
}
if (tbb != "") {
i++;
}
if (i >= 2) {
//do something
}
Any better thoughts?
if(tbb == null || tbb == ''){...}
And the same for the rest.
var twoAreEmpty = $("#total1, #total2, #total3").find("span:empty").length === 2;
var twoblank =
$("#tota11 span, #total2 span, #total3 span")
.filter(function(index){
return !$(this).text().replace(/^\s+|\s+$/g, '');
})
.length === 2;
Also, you probably mean #total1, not #tota11 - just sayin.
if (tab == "") should be enough shouldn't it?
Does .text() ever return blank?
var filtered = [tmb, tbb, tab].filter(function( str ) {
return !str.length;
});
if( filtered.length === 2 ) {
console.log('yay, two empty values: ', filtered);
}
Just try it.
var i = 0;
if(tbb.length == 0 )
{
i++
}
if(tmb.length == 0 )
{
i++
}
if(tab.length == 0 )
{
i++
}
if(i >=2)
{
//perform operation
}
It's been a while, but this is going to be a single-line solution for what you want.
if (((tab == '' ? 1 : 0) + (tmb == '' ? 1 : 0) + (tbb == '' ? 1 : 0)) > 1){
// Do Something
}
All valid answers, but forgetting about undefined :)
if(tbb === '' || tbb === null || tbb === undefined){ // do stuff };
I'd recommend making it a function which could return true/false :)

Categories

Resources