Understanding this Javascript function - javascript

I am continuing a project. And this is the only thing I do not understand. It is the key function for assembling a filter string to be used for sql query. This function is invoke via onclick of a button.
My problem is the value for query is taken from $_REQUEST['FILTER'].
<input id="HDN_FILTER" name="FILTER" type="hidden" value="<?php echo $_REQUEST['FILTER']; ?>">
At first $_REQUEST['FILTER'] is empty. Then upon pressing the submit button it assembles and return the string. But I don't understand how it assembled the string. Because it seems the function get its value from this input. But it's value is empty. So the function should received empty from this input. It's like going in circles
Example what does "" != means in javascipt anyway?
An example of the assembled string is ""DELIVER_STORE_ACCOUNT=ALL^STORES_ACCOUNT=ALL^ACTIVE=1^PART_NUMBER=ALL^NEW_PART_NUMBER=ALL""
And I see the join("^") part in the function. And it seems this line assembles it. But why is it inside a switch parenthesis?
function SUBMIT(e, t) {
array_Filter = new Array;
for (i in array_Dropdown) {
if (varField = array_Dropdown[i], varID = "SEL_" + varField, aryTemp = new Array, -1 != document.getElementById(varID).selectedIndex)
for (i = 0; i < document.getElementById(varID).options.length; i++)
document.getElementById(varID).options[i].selected === !0 && (aryTemp[aryTemp.length] = document.getElementById(varID).options[i].value);
aryTemp.length > 0 && (array_Filter[varField] = aryTemp)
}
"" != document.getElementById("HDN_SEARCH").value && (aryTemp.SEARCH = document.getElementById("HDN_SEARCH").value), array_Filter_Temp = new Array;
for (i in array_Filter)
array_Filter_Temp[array_Filter_Temp.length] = i + "=" + array_Filter[i].join("|");
switch (varFilter = array_Filter_Temp.join("^"), document.getElementById("HDN_FILTER").value = varFilter, document.getElementById("HDN_EXCEL").value = 1 == e ? 1 : 0, !0) {
case 1 == t:
document.getElementById("HDN_OVERRIDE").value = 1;
break;
case 0 == t:
document.getElementById("HDN_OVERRIDE").value = 0;
break;
case-1 == t:
}
varTXTBOX = document.getElementById("TXT_SEARCH").value;
alert(varTXTBOX);
document.getElementById("FORM1").submit()
}

Whoever wrote this code was trying to obfuscate it, making it hard for anyone else to understand what it does, perhaps because the result is sent to a SQL query, as you stated. Of course, if you want to hide anything from your users, specially SQL commands, implement it server-side.
1) The "" != part:
"" != document.getElementById("HDN_SEARCH").value // left side
&& // logical AND
(aryTemp.SEARCH = document.getElementById("HDN_SEARCH").value), // right side
array_Filter_Temp = new Array; // another statement
Here he's taking advantage of the short-circuit evaluation, if the left side of the expression evaluates to false, then the right side isn't executed. The next statement after the , is always executed (read more about the comma operator). So it's the same as writing:
if (document.getElementById("HDN_SEARCH").value != "") {
aryTemp.SEARCH = document.getElementById("HDN_SEARCH").value
}
array_Filter_Temp = new Array;
2) The switch part:
switch (
varFilter = array_Filter_Temp.join("^"),
document.getElementById("HDN_FILTER").value = varFilter,
document.getElementById("HDN_EXCEL").value = 1 == e ? 1 : 0,
!0
) {
The first two are trivial. On the third one, he is assigning HDN_EXCEL based on the value of e. Adding parenthesis makes it clearer: document.getElementById("HDN_EXCEL").value = (1 == e) ? 1 : 0
The !0 is there just to make sure the rest of the switch is executed (it evaluates to true). If it was 0 or false, then HDN_OVERRIDE would never be assigned to a value.
So that whole set could be rewritten as:
varFilter = array_Filter_Temp.join("^");
document.getElementById("HDN_FILTER").value = varFilter;
document.getElementById("HDN_EXCEL").value = (e == 1) ? 1 : 0;
switch (t) {
case 1:
document.getElementById("HDN_OVERRIDE").value = 1;
break;
case 0:
document.getElementById("HDN_OVERRIDE").value = 0;
break;
}
3) The first for loop: (you haven't asked, but here it goes anyway)
for (i in array_Dropdown) {
if (
varField = array_Dropdown[i],
varID = "SEL_" + varField,
aryTemp = new Array,
-1 != document.getElementById(varID).selectedIndex
)
for (i = 0; i < document.getElementById(varID).options.length; i++)
document.getElementById(varID).options[i].selected === !0 && (aryTemp[aryTemp.length] = document.getElementById(varID).options[i].value);
aryTemp.length > 0 && (array_Filter[varField] = aryTemp)
}
Again the use of the , operator to execute all commands and return the value of the last one to the if, which is -1 != document.getElementById(varID).selectedIndex, so the second for loop will run only if the element in varID has a selectedIndex.
The === !0 is the same as === true.
This could be rewritten as:
for (key in array_Dropdown) {
varField = array_Dropdown[key];
varID = "SEL_" + varField;
aryTemp = new Array;
if (document.getElementById(varID).selectedIndex != -1) {
for (i = 0; i < document.getElementById(varID).options.length; i++) {
if (document.getElementById(varID).options[i].selected) {
aryTemp[aryTemp.length] = document.getElementById(varID).options[i].value;
}
}
}
if (aryTemp.length > 0) {
array_Filter[varField] = aryTemp;
}
}
As a side note, if you can, I suggest you refactor this code, send only the collected data to the server and do all the transformation needed on the server-side.

Related

How to remove the 1st character if a comma from a cell value using GAS?

I'm iterating over a range and the rows whose conditions are met, gets one of its column's cell value pushed into an array. Now, from the second iteration on, there shouldn't be a , at the beginning, but this is naturally inherited.
for (var a = 0; a < dataRng.length; a++) {
if (dataRng[a][1] == true && dataRng[a][0] == 'SHIPPED' && dataRng[a][40] != 'Yes') {
msgBody.push(dataRng[a][37].toString().replace(',', '') + '\n');
var iteratedRow = a + 3
sheet.getRange(iteratedRow, 41).setValue('Yes')
}
}
This is the result now:
So, right at the beginning of the second row, that comma shouldn't be there and it should begin with 'NPA...'
Thank you!
I think this is what you're looking for. There's probably cleaner ways of doing it, but it collects the value, then tests for a comma, then pushes to an array without the comma if one existed.
for (var a = 0; a < dataRng.length; a++) {
if (dataRng[a][1] == true && dataRng[a][0] == 'SHIPPED' && dataRng[a][40] != 'Yes') {
var aValue = dataRng[a][37].toString().replace(',', '') + '\n';
if (aValue.charAt(0)=== ","){
aValue = aValue.slice(1);
}
msgBody.push(aValue);
var iteratedRow = a + 3
sheet.getRange(iteratedRow, 41).setValue('Yes')
}
}

How to fix this "if" statement

I don't really know the correct format to this if statement. I want it to count the frequency each word in my txt file was used.
function countWords(array, word, index) {
var count = 0;
var value = " "
for (var i = 0; i < array.length; i++) {
if (array[i] == 0 && value == word)
count++;
}
}
if (getUserSelectionForm.problem.value == "pay") {
countWords(working2DArray, "pay", 0)
if (getUserSelectionForm.problem.value == "staffing") {
countWords(working2DArray, "staffing", 0)
if (getUserSelectionForm.problem.value == "hours") {
countWords(working2DArray, "hours", 0)
if (getUserSelectionForm.problem.value == "management") {
countWords(working2DArray, "management", 0)
console.log(countWords)
document.getElementById('section2').innerHTML = "The selected word appears " + countWords + " times in the array."
}
Try not to use multiple IF statements and use a switch statement instead. Makes code much clearer and cleaner.
E.g.
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch
So:
var p = getUserSelectionForm.problem.value;
switch (p) {
case 'pay':
countWords(working2DArray, "pay", 0);
break;
case 'staffing':
countWords(working2DArray, "staffing", 0);
}
You are making three mistakes in code:
You are missing some of the closing curly braces } of you if blocks.
You do not return anything from function. You should return count.
countWords is a function you don't need to display that. You need to display its result.
You can make your code much simpler. You don't need these if statements at all because you are passing the same value of getUserSelectionForm.problem.value to the function so directly pass it.
function countWords(array, word, index) {
var count = 0;
var value= " "
for(var i = 0; i < array.length; i++){
if(array[i] == 0 && value == word)
count++;
}
return count;
}
let word = getUserSelectionForm.problem.value
document.getElementById('section2').innerHTML = `The selected word appears ${countWords(working2DArray,word,0)} times in array`
If you want to only check for few items then use create a array of "pay","staffing"... and use includes() on it
let word = getUserSelectionForm.problem.value
if(["pay","staffing","hours","management"].includes(word)){
document.getElementById('section2').innerHTML = `The selected word appears ${countWords(working2DArray,word,0)} times in array`
}
In my understanding , you want to trigger the function whenever problem.value ==='pay'||'staffing'||'hours'||'management' ,here is clearer version for your reference:
var problemValue = getUserSelectionForm.problem.value;
var isProblemValueMatch = ["pay", "staffing" ,"hours", "management"].includes(problemValue);
if (isProblemValueMatch ) {
var countWords = working2DArray.filter(function(v) {
return v === problemValue;
}).length;
console.log(countWords)
document.getElementById('section2').innerHTML = "The selected word appears " + countWords + " times in the array."
}

How To Break Out Of arr.find()?

This might not be best practice, but I was wondering if it's possible to break from the arr.find() method.
Here's some code that I was working on that I've since redone with a loop but I was wondering why this is not allowed?
Any help is appreciated!
I understand this isn't the best approach to the problem at hand I'm just curious to why the break doesn't work as intended where am I messed up in my thinking?
//Using the JavaScript language, have the function SimpleSymbols(str) take the str parameterbeing passed and determine if it is an acceptable sequence by either return in the string true or false. The str parameter will be composed of + and = symbols with several letters between them (ie. ++d+===+c++==a) and for the string to be true each letter must be surrounded by a + symbol. So the string to the left would be false. The string will not be empty and will have at least one letter.
//loop through Array
//Determine if letter is surrounded by +
//If yes continue on and return true
//If no break loop and return false
function SimpleSymbols(str){
str = str.split('');
var pass = null;
function finder(char){
if (char.length === 1 && char.match(/[a-z]/i)){
var firstPlus = str.indexOf(char)- 1;
var secondPlus = str.indexOf(char)+ 1;
console.log(str[firstPlus]);
if (str[firstPlus] === '+' && str[secondPlus] === '+'){
pass = 'true';
} else {
pass = 'false'
break;
}
}
}
str.find(finder);
return pass
}
SimpleSymbols('++d+===+c++==a++q++');
This code will break loop in your case after 5 iterations:
SimpleSymbols('++-+d+===*c+3++==a++q-3++');
function SimpleSymbols(str){
str = str.split('');
var pass = null;
str.find(finder);
function finder(char, i){
console.log('Iteration No.' + i);
if (str.indexOf(char) && char.length === 1 && char.match(/[a-z]/i)){
var firstPlus = str.indexOf(char)- 1;
var secondPlus = str.indexOf(char)+ 1;
//console.log(str[firstPlus]);
if (str[firstPlus] === '+' && str[secondPlus] === '+'){
pass = 'true';
return pass;
} else {
pass = 'false';
}
}
}
console.log('FINAL RESULT = ' + pass);
return pass;
}

How can I use javascript to create a string consisting of every ISO/IEC 8859-1 character possible?

I want to create a string consisting of every character possible and see if any of the popular QR readers are able to read each and every char from this QR Barcode.
My problem is that I simply don't know how to create an object as a byte so that it appears as a IEC 8859 character. I've tried the Typed Arrays, but unable to achieve printing out each character and assigning it to the Telerik / Kendo control
How do I use JS to create a string of ISO/IEC 8859-1 characters, and assign it to the control linked above?
I wrote this function that takes a JavaScript number and determines if it's in the ISO/IEC 8859-1 codespace. Using this which String.fromCharCode allows you to construct the string you're looking for.
function inIsoIec8859_1(code) {
if (typeof code !== "number" || code % 1 !== 0) {
throw Error("code supplied is not a integer type.")
}
if (code > 255 || code < 32 || (code > 126 && code < 160)) {
return false;
}
return true;
}
var isoLatinCodespace = "";
var code = 0;
for (; code < 255; code += 1) {
if (inIsoIec8859_1(code)) {
var current = String.fromCharCode(code);
isoLatinCodespace = isoLatinCodespace + current;
}
}
http://dojo.telerik.com/IGoT/12
Because you accepted my original answer, it is above this line, unedited. I realized something after I posted that could be important.
If you plan on getting this value in a loop, this will serve your needs much better.
var MyApp = {
isoLatinString : (function() {
var isoLatinCodespace = "";
return function () {
if (!isoLatinCodespace) {
function inIsoIec8859_1(code) {
if (typeof code !== "number" || code % 1 !== 0) {
throw Error("code supplied is not a integer type.")
}
if (code > 255 || code < 32 || (code > 126 && code < 160)) {
return false;
}
return true;
}
var code = 0;
for (; code < 255; code += 1) {
if (inIsoIec8859_1(code)) {
var current = String.fromCharCode(code);
isoLatinCodespace = isoLatinCodespace + current;
}
}
}
return isoLatinCodespace;
}
}())
}
Then later using MyApp.isoLatinString(). This new code only generates the string once, even if called multiple times. MyApp can be any object you're using to contain your application.

Number expected error on sort

Other browsers work fine but in IE i get Number Expected when using the following code and it runs into a null object on the sort function.
http://jsfiddle.net/R3ndd/2/
function list_response(jsonData) {
"use strict";
var lists = document.getElementById("lists"), anchors = document.getElementById("anchors"), jItems = jsonData.items;
var results = [], anks = [], vList, pListName, item, videoItem;
var i, j, jLen, iLen = jItems.length;
for (var i = 0; i < iLen; i++) {
if(jItems[i] != null ){
jItems[i].nameLower = jItems[i].name.toLowerCase();
}
}
jItems.sort(function (a, b) {
if(a != null && b != null){
return a.nameLower.localeCompare(b.nameLower);
}
});
Any suggestions? Thanks!
My Solution
I decided to remove the null object (which works) from json using the following:
var y;
for (var x in jItems) {
if ( Object.prototype.hasOwnProperty.call(jItems,x)) {
y = jItems[x];
if (y==="null" || y===null || y==="" || typeof y === "undefined") {
delete jItems[x];
}
}
}
Don't know why IE does that, but it is it's habit to trouble us good people :). Well, I think this will be better way.
/* NOT NEEDED.
for (var i = 0; i < iLen; i++) {
if(jItems[i] != null ){
jItems[i].nameLower = jItems[i].name.toLowerCase();
}
}*/
jItems.sort(function (a, b) {
return a && b ? a.toLowerCase().localeCompare(b.toLowerCase()) : 0;
});
UPDATE:
Well, I think I know where IE is troubling. Sorry MS, this time IE hasn't any fault. What happened was that in case where either a or b were null/''/false (or any falsy value), your callback didn't return any value. That explians the 'Number expected' error. But I took care of that, so my answer will probably work. :)

Categories

Resources