Javascript function returns undefined instead of int - javascript

My js/jquery function does not work properly and instead of INT returns undefined.
function __getLastSelectedCategory(table_id) {
if ( jQuery('.categories_table[data-table-id="1"]').find('td.active').length > 0 ){
console.log('check1');
if (table_id != '0') {
console.log('check2');
var checkTableId = parseInt(table_id) - 1;
var table = jQuery('.cl_categories_display ').find('table[data-table-id="' + checkTableId + '"]');
if (table.find('td.active').length > 0) {
console.log('check3');
console.log('table id: ' + table.find('td.active').data('category-id'));
return table.find('td.active').data('category-id');
} else {
console.log('check4');
__getLastSelectedCategory(checkTableId);
}
} else {
console.log('check5');
var lastTable = jQuery('.cl_categories_display ').find('table:last');
var lastTableId = lastTable.data('table-id');
if (lastTable.find('td.active').length > 0) {
console.log('check6');
return lastTable.find('td.active').data('category-id');
} else {
console.log('check7');
__getLastSelectedCategory(lastTableId);
}
}
} else {
console.log('check8');
return null;
}
}
when I run this function I see in console:
check 1
check 5
check 7
check 1
check 2
check 3
table id: 1
last cat: undefined
so the recursion works fine, but instead of integer (console printed "table id: 1") ir returns undefined. What could be wrong?

You forgot return from recurse call: It returned value from the inner function to the outer, but did not return it from outer function to the caller. Try this:
function __getLastSelectedCategory(table_id) {
if ( jQuery('.categories_table[data-table-id="1"]').find('td.active').length > 0 ){
console.log('check1');
if (table_id != '0') {
console.log('check2');
var checkTableId = parseInt(table_id) - 1;
var table = jQuery('.cl_categories_display ').find('table[data-table-id="' + checkTableId + '"]');
if (table.find('td.active').length > 0) {
console.log('check3');
console.log('table id: ' + table.find('td.active').data('category-id'));
return table.find('td.active').data('category-id');
} else {
console.log('check4');
return __getLastSelectedCategory(checkTableId);
}
} else {
console.log('check5');
var lastTable = jQuery('.cl_categories_display ').find('table:last');
var lastTableId = lastTable.data('table-id');
if (lastTable.find('td.active').length > 0) {
console.log('check6');
return lastTable.find('td.active').data('category-id');
} else {
console.log('check7');
return __getLastSelectedCategory(lastTableId);
}
}
} else {
console.log('check8');
return null;
}
}

Related

This palindrome code returns error only while submitting in leetcode, its working in my local for same testcase

This code return "false" for test input "1" only when I submit in leet code. It's working when I do it in my local or leet code editor for the same input
var temp = 0;
var rev = 0;
var palindromeCheck = function (org) {
temp = org % 10;
rev = rev * 10 + temp;
org = parseInt(org / 10);
if (org > 0) {
palindromeCheck(org);
}
return rev;
};
var isPalindrome = function (x) {
if (x == 0) {
return true;
}
else if(x > 0) {
var value = palindromeCheck(x);
if (value === x) {
return true;
}
else {
return false;
}
}
else {
return false;
}
};
your palindromeCheck() function return a number. The problem comes from this part, where you strictly compare a number and a string:
if (value === x) {
return true;
}
else {
return false;
}
try to do :
if (value == x) {
return true;
}
else {
return false;
}
or
return (value == x);
else you can just use parseInt() function.

Why my array data does not print in render function REACTJS?

I am stuck in reactjs.
I have a function in which there is an array containing some values, but when I want to access that array in render function and pass it using props to another function, it returns a blank array.
what should I do to resolve this problem?
Like this:
In Function:
this.usersAnswerXML = ["ID0", "ID1", "ID2"]
In Render:
this.usersAnswerXML = []
Here is my code, what am I doing wrong?
handleSplitContentClick(contentId, selectionType) {
let isCorrect
if (selectionType == 'selected') {
const index = this.correctAnswers.indexOf(contentId);
if (index > -1) {
this.userCorrectAnswers.push(contentId);
if (this.correctAnswers.length === this.userCorrectAnswers.length &&
this.userUncorrectAnswer.length == 0) {
isCorrect = this.correct
} else {
isCorrect = this.incorrect
}
} else {
this.userUncorrectAnswer.push(contentId);
isCorrect = this.incorrect
}
} else if (selectionType == 'disselected') {
const index = this.correctAnswers.indexOf(contentId);
if (index > -1) {
this.userCorrectAnswers.splice(index, 1);
isCorrect = this.incorrect
} else {
this.userUncorrectAnswer.splice(index, 1);
if (this.correctAnswers.length === this.userCorrectAnswers.length &&
this.userUncorrectAnswer.length == 0) {
isCorrect = this.correct
} else {
isCorrect = this.incorrect
}
}
}
this.userAnswerXML = this.userCorrectAnswers.join(',')
this.usersAnswerXMLs = this.userAnswerXML + ',' +
this.userUncorrectAnswer.join(',')
this.usersAnswerXML = this.usersAnswerXMLs.split(',')
console.log(this.usersAnswerXML)
if (window.uaXML) {
this.userAnswerXML = window.uaXML
console.log(this.userAnswerXML + "data")
}
// this.usersAnswerXML = window.uaXML
console.log(window.uaXML)
this.userAnswerXML = "<smans type='4'><div id='textID0' userAns='" +
this.usersAnswerXML + "'></div></smans>"
$("#special_module_user_xml").val(this.userAnswerXML )
console.log(this.usersAnswerXML)
}
} // Editor's note: this is an extra curly brace
render() {
if (this.props.remedStatus) {
console.log(this.usersAnswerXML)
console.log("inside remed")
return (
<HotspotRemed
xml={this.receivedXML}
userXml={this.usersAnswerXML}
correctAnswer ={this.ansString}
type={this.splitType}
/>
)
} else {
return (
<div className="previewtemplate" style ={template}>
{this.templateArea(this.state.templateType)}
</div>
);
}
}
} // Editor's note: another extra curly brace
} // Editor's note: another one again

JavaScript. Please advise on better code reuse and/or structure

As the title suggests, A better coding structure or implementation for my JavaScript below. This checks a ID element values from a form before submitting to a database.
I'm interested to know if I could have reduced the code size/could have implemented reuse of code which will give me some tips for the future!
Thanks.
function validateRunnerID()
{
var runnerID = document.getElementById('RunnerID').value;
if (isNaN(runnerID) || runnerID < 1 || runnerID > 9999)
{
return "RunnerID: Enter a Integer Value between 1-9999 \n\n";
}else{
return "";
}
}
function validateEventID()
{
var eventID = document.getElementById('EventID').value;
if (isNaN(eventID) || eventID < 1 || eventID > 9999)
{
return "EventID: Enter a Integer Value between 1-9999 \n\n";
}else{
return "";
}
}
function validateDate()
{
var checkDate= /^[0-9]{4}\-(0[1-9]|1[012])\-(0[1-9]|[12][0-9]|3[01])/;
var date= document.getElementById('Date');
var tof= date.value.match(checkDate);
return tof? "" : "Date: Enter a Valid Date with parameters: YYYY-MM-DD \n\n";
}
function validateFinishTime()
{
var finishTime = document.getElementById("FinishTime").value;
if (finishTime.match(/^[0-9]{2}:[0-9]{2}:[0-9]{2}$/))
{
return ""
}else{
return "Finish Time: Enter a valid Time with parameters: HH:MM:SS \n\n";
}
}
//
//
function validatePosition()
{
var position = document.getElementById('Position').value;
if (position.length == 0)
{
document.getElementById('Position').value = -1;
return "";
}else{
return "";
}
}
function validateCategoryID()
{
var categoryID = document.getElementById('CategoryID').value;
if (categoryID.length == 0)
{
document.getElementById('CategoryID').value = -1;
return "";
}else{
return "";
}
}
function validateAgeGrade()
{
var ageGrade = document.getElementById('AgeGrade').value;
if (ageGrade.length == 0)
{
document.getElementById('AgeGrade').value = -1;
return "";
}else{
return "";
}
}
function validatePB()
{
var pBest = document.getElementById('PB').value;
if (pBest.length == 0)
{
document.getElementById('PB').value = 0;
return "";
}else{
return "";
}
}
//
//
function validateForm()
{
var result = validateRunnerID() + validateEventID() + validateDate() + validateFinishTime() + validatePosition() + validateCategoryID() + validateAgeGrade() + validatePB();
if ( result == "" )
{
alert("Data Accepted and Submitted \n\n");
return true;
}else{
alert("Please Fix Errors Listed: \n\n" + result);
return false;
}
}
One thing you can do is to accept an elementId as input to your validation functions. This allows to reuse the same logic for different fields.
For example:
function validate4DigitInt(elementId)
{
var value = document.getElementById(elementId).value;
if (isNaN(value) || value < 1 || value > 9999)
{
return elementId + ": Enter a Integer Value between 1-9999 \n\n";
}else{
return "";
}
}
Now you can validate both RunnerId and EventId using the same function:
var result="";
result+=validate4DigitInt("RunnerId");
result+=validate4DigitInt("EventId");

Previous or next element in array based on string "direction"

I'm trying to make function that will return next or previous item in array, based on parameter "direction".
For example I have array = ['ferrari', 'bmw', 'merc', 'bugatti'] and I want my my function to return 'bugatti' IF currentPointer = 'ferrari' and direction = 'left'
nextPrev(array,direction,currentPointer)
In php we have function next() which moves the internal pointer ... but I don't know how to do it in javascript ...
Try Something like this.
Using the numerical locations of the array and conditionally cycle through:
var array = ['ferrari', 'bmw', 'merc', 'bugatti'];
var returnedElement = nextPrev(array, "left", "ferrari");
// Show Returned Value (Console)
console.log(returnedElement);
function nextPrev(array, direction, currentPointer) {
var arraySize = array.length - 1;
var currentIndex = array.indexOf(currentPointer);
if (direction === "left") {
// Decrease array by one
if (currentIndex == 0) {
// Return Previous (Max Array)
return array[arraySize]
} else {
return array[currentIndex - 1]
}
} else if (direction === "right") {
// Increase array by one
if (currentIndex == arraySize) {
// Go to zero position
return array[0]
} else {
return array[currentIndex + 1]
}
} else {
console.log("Use either 'left' or 'right'");
}
}
The basic idea would be:
function nextPrev(array, direction, currentPointer) {
var index = array.indexOf(currentPointer);
if (direction=="left") {
return array[index == 0 ? array.length-1 : index-1];
} else if (direction=="right") {
return array[index == array.length-1 ? 0 : index+1];
} else {
// default action or throw error
}
}
You can reorganize this a bit:
function nextPrev(array, direction, currentPointer) {
var index = array.indexOf(currentPointer);
var len = array.length;
if (direction=="left") {
index--;
} else if (direction=="right") {
index++
} else {
// default action or throw error
}
return array[(index + len) % len];
}
You might want to add a check that array.indexOf returns a valid index (in case currentPointer contains something not in array).
You can write something like this:
function makeDirectionalIterator(array){
var currIndex = 0;
return {
nextPrev: function(direction){
if(direction === 'left') {
return currIndex < array.length-1 ?
{value: array[++currIndex], done: false} :
{done: true};
}
else {
return currIndex > 0 ?
{value: array[--currIndex], done: false} :
{done: true};
}
},
current: function() {
return { value: array[currIndex] };
}
}
}
Then you can use it like the following
var itr = makeDirectionalIterator(array);
itr.current().value;
itr.nextPrev('left').value;
itr.nextPrev('left').done;

else if is not printing the console value

I have JavaScript code which displays a multi coffee value.
If I am trying to display a single value coffee, its not going inside the else if.
I modified existing code but getting an undefined error.
Can you tell me how to fix it?
var multCoffees = false;
var singleCoffee = false;
if (Coffees.length > 1) {
multCoffees = true;
}
if (Coffees.length > 1) {
singleCoffee = true;
}
if (apptTimeCell) {
apptTimeHTML = MyDay.dish(allData, multCoffees, singleCoffee);
apptTimeCell.innerHTML = apptTimeHTML;
} else {
apptTimeCell = Util.cep("span", {
className: "appt-time"
});
patientRowTD.insertBefore(apptTimeCell, patCell);
}
dish: function (allData, multCoffees, singleCoffee) {
if (multCoffees) {
var htmlArr = [];
htmlArr.push(allData.APPT_TIME_DISPLAY, "<br/><span class='sub-detail'>", allData.MNEMONIC, "</span>");
console.log("multiCoffee" + allData.PROVIDER_MNEMONIC);
return htmlArr.join("");
} else if (singleCoffee) {
console.log("inside if" + allData.PROVIDER_MNEMONIC);
var htmlArr = [];
htmlArr.push(allData.APPT_TIME_DISPLAY, "<br/><span class='sub-detail'>", allData.PROVIDER_MNEMONIC, "</span>");
console.log("singleCoffee" + allData.PROVIDER_MNEMONIC);
return htmlArr.join("");
} else {
return allData.APPT_TIME_DISPLAY;
}
},
Working code:
var multCoffees = false;
if (Coffees.length > 1) {
multCoffees = true;
}
if (apptTimeCell) {
apptTimeHTML = MyDay.dish(allData, multCoffees);
apptTimeCell.innerHTML = apptTimeHTML;
} else {
apptTimeCell = Util.cep("span", {
className: "appt-time"
});
patientRowTD.insertBefore(apptTimeCell, patCell);
}
dish: function (allData, multCoffees) {
if (multCoffees) {
var htmlArr = [];
htmlArr.push(allData.APPT_TIME_DISPLAY, "<br/><span class='sub-detail'>", allData.MNEMONIC, "</span>");
console.log("multiCoffee" + allData.PROVIDER_MNEMONIC);
return htmlArr.join("");
} else {
return allData.APPT_TIME_DISPLAY;
}
},
Suppose Coffees.length is 2. You do this...
if (Coffees.length > 1) {
multCoffees = true;
}
...and 2 > 1, so now multCoffees is true, but then you do this, which checks the same thing...
if (Coffees.length > 1) {
singleCoffee = true;
}
and, since 2 > 1 still, now BOTH multCoffees AND singleCoffee are true. So when you try to do
if (multCoffees) {
...
} else if (singleCoffee) {
...
}
the first if branch is true, so it is executed, and the else branch is thus ignored (despite also being true). You probably meant to instead start with
if (Coffees.length == 1) {
singleCoffee = true;
} else if (Coffees.length > 1) {
multCoffees = true;
}
replace your first two ifs with this block:
if (Coffees.length == 1) {
singleCoffee = true;
}
else if(Coffees.length > 1){
multCoffees = true;
}
and then try it again!

Categories