I'm struggling in a recursive Javascript function to find a specific subdirectory. This is my code:
function navigateToParent() {
var parentFullPath = parentDirectory(); // gets the full Path String
if (parentFullPath != null) {
var parent = getDirectoryByName(parentFullPath, rootDirectory);
// set the parent directory object as the current one
currentDirectory(parent);
}
}
function getDirectoryByName(fullName, myDirectory) {
if (myDirectory.fullName == fullName) {
return myDirectory;
} else {
var subs = myDirectory.subDirectories;
for (i = 0; i < subs.length; i++) {
return getDirectoryByName(fullName,subs[i]);
}
}
}
Every directory object has the properties fullName(string),subDirectories(array of directories) and files(array of files). My aim is to get the correct directory object, where it's fullName is matching.
I know, that i have to break the for loop in some way, but i don't know how to do it exactly.
After overthinking the logic i came to this solution (seems to work):
function getDirectoryByName(fullName, myDirectory) {
if (myDirectory.fullName == fullName) {
return myDirectory;
} else {
var subs = myDirectory.subDirectories;
for (i = 0; i < subs.length; i++) {
var match = getDirectoryByName(fullName, subs[i]);
if (typeof match !== "undefined"){
return match;
}
}
}
}
Related
When setting value of object to true it looks and seems it changed it but I still cant use it(as it stayed false).
validateNextMove() {
Card.setArrayNextMoveValid(this.cardRepository.findAll(), false);
let client = this.clientRepository.findByTurn(true);
let provjera = 0;
if (client instanceof UNOClient) {
let cards = client.getCards();
for (let i = 0; i < cards.length; i++) {
if (this.cardCanBePlaced(cards[i])) {
provjera++;
cards[i].setNextMoveValid(true);
console.log(cards[i].getNextMoveValid());
console.log(provjera);
}
}
if (provjera == 0) {
for (let i = 0; i < cards.length; i++) {
cards[i].setNextMoveValid(true);
console.log(cards[i].getNextMoveValid());
console.log(provjera);
}
}
How do I fix this ?
this is my method for checking if card can be place:
cardCanBePlaced(card){
let current = this.discardDeck.slice(-1)[0];
if(typeof current === 'undefined'){
return true;
}
//Check if card is allowed
if(
card.getColor() === current.getColor()
){
return true;
}
return false;
}
if in above mtehod i add global variable to count if there is any available it still doesnt make it work, something like this(counter++ if there is available card of that color)
if(card.getColor()!= current.getColor() && counter==0){
return true;
}
I'm trying the following code:
var var1 = "";
var var2 = "test";
var var3 = "";
vars = new Array('var1','var2','var3');
var count = 0;
for (var i = 0; i < vars.length; ++i) {
var name = vars[i];
if (field_is_empty(name)) {
count++;
}
}
console.log(count);
function field_is_empty(sValue) {
if (sValue == "" || sValue == null || sValue == "undefined")
{
return true;
}
return false;
}
The result here should have been count = 2 because two of the variables are empty but it's always 0. I guess it must something when using if (field_is_empty(name)) because it might not getting the name converted to the name of the actual var.
PROBLEM 2# Still related
I've updated the code as Karthik Ganesan mentioned and it works perfectly.
Now the code is:
var var1 = "";
var var2 = "test";
var var3 = "";
vars = new Array(var1,var2,var3);
var count = 0;
for (var i = 0; i < vars.length; ++i) {
var name = vars[i];
if (field_is_empty(name)) {
count++;
}
}
console.log(count);
function field_is_empty(sValue) {
if (sValue == "" || sValue == null || sValue == "undefined")
{
return true;
}
return false;
}
And the problem is that if add a new if statement something like this:
if (count == '3') {
console.log('AllAreEmpty');
} else {
for (var i = 0; i < vars.length; ++i) {
var name = vars[i];
if (field_is_empty(name)) {
//Set the empty variables as "1900-01-01"
variableService.setValue(name,"test");
}
}
}
It does nothing and I've tested using variableService.setValue('var1',"test") and it works.
PS: The variableService.setValue is a function controlled by the software I don't know exactly what it does I know if use it like mentioned on above line it works.
In your first attempt you used the variable names as strings when you created an array. You need to either use the values themselves:
vars = new Array(var1,var2,var3);
or if you insist to use them by their names, then you need to find them by names when you use them:
if (field_is_empty(window[name])) {
It does nothing
That's not really possible. It could throw an error, or enter the if or enter the else, but doing nothing is impossible. However, since you intended to use the variables by name in the first place (probably not without a reason) and then you intend to pass a name, but it is a value and it does not work as expected, I assume that your initial array initialization was correct and the if should be fixed like this:
var var1 = "";
var var2 = "test";
var var3 = "";
vars = new Array(var1,var2,var3);
var count = 0;
for (var i = 0; i < vars.length; ++i) {
var v = window[vars[i]]; //You need the value here
if (field_is_empty(v)) {
count++;
}
}
console.log(count);
if (count == '3') {
console.log('AllAreEmpty');
} else {
for (var i = 0; i < vars.length; ++i) {
var v = window[vars[i]];
if (field_is_empty(v)) {
//Set the empty variables as "1900-01-01"
variableService.setValue(vars[i],"test");
}
}
}
function field_is_empty(sValue) {
if (sValue == "" || sValue == null || sValue == "undefined")
{
return true;
}
return false;
}
You definitely incorrectly initialize array, you put strings "var1", "var2", "var3" instead of references to strings (variables).
Try this:
vars = new Array(var1,var2,var3);
Your array is wrong
it should be
vars = new Array(var1,var2,var3);
here is the jsfiddle
When parsing documents using the excellent libxmljs library in Node.js, I stumbled across a case where a lot of nested elements were found, and the only thing I had to do was create a JS object from it.
Here is what the code looks like :
if (node.type() == 'element') {
switch(node.name()) {
case 'element1': {
myObject.element1 = {}
for (var i = 0; i < node.childNodes().length; i++) {
if(node.type() == 'element') {
switch(node.name()) {
case 'element2': {
myObject.element1.element2 = node.text()
...
}}}}}}}}
/* didn't count the number of closing brackets, but you get the idea ^_^ */
Is there a faster or built-in way to do such things, create an object from an XML string (or part of it) using libxmlJS ?
Note that, if it helps, the parsed XML must be validated against a XTD schema (which can really easily be done using this library)
Thanks
Here is some non-working code that can be found on this article :
function XML2jsobj(node) {
var data = {};
// append a value
function Add(name, value) {
if (data[name]) {
if (data[name].constructor != Array) {
data[name] = [data[name]];
}
data[name][data[name].length] = value;
}
else {
data[name] = value;
}
};
// element attributes
var c, cn;
for (c = 0; cn = node.attributes[c]; c++) {
Add(cn.name, cn.value);
}
// child elements
for (c = 0; cn = node.childNodes[c]; c++) {
if (cn.nodeType == 1) {
if (cn.childNodes.length == 1 && cn.firstChild.nodeType == 3) {
// text value
Add(cn.nodeName, cn.firstChild.nodeValue);
}
else {
// sub-object
Add(cn.nodeName, XML2jsobj(cn));
}
}
}
return data;
}
From that code, I could build something that seems to work with the latest libxmljs release, here it is :
function XML2jsobj(node) {
var data = {};
// append a value
function Add(name, value) {
if (data[name]) {
if (data[name].constructor != Array) {
data[name] = [data[name]];
}
data[name][data[name].length] = value;
}
else {
data[name] = value;
}
};
for (var c = 0; c < node.attrs().length; c++) {
var cn = node.attrs()[c];
Add(cn.name, cn.value);
}
// child elements
for (var c = 0; c < node.childNodes().length; c++) {
var cn = node.childNodes()[c];
if (cn.type() == 'element') {
if (cn.childNodes().length == 1 && cn.childNodes()[0].type() == 'text') {
// text value
Add(cn.name(), cn.childNodes()[0].text());
}
else {
// sub-object
Add(cn.name(), XML2jsobj(cn));
}
}
}
return data;
}
I hope this will have helped someone.
i have a jsp page and call a JS function which is in some abc.js file from this JSP page.
i have included this js file to jsp page.
JSP JavaScript Code:-
function doFinish(tableId, col, field)
{
var oldselectedCells = "";
var selItemHandle = "";
var selRightItemHandle = "";
var left = -1;
var right = -1;
// Get the table (tBody) section
var tBody = document.getElementById(tableId);
// get field in which selected columns are stored
var selectedCellsFld = document.getElementById(tableId + datatableSelectedCells);
selectedCellsFld.value = oldselectedCells;
for (var r = 0; r < tBody.rows.length; r++)
{
var row = tBody.rows[r];
if (row.cells[col].childNodes[0].checked == true)
{
selectedCellsFld.value = oldselectedCells +
row.cells[col].childNodes[0].id;
selItemHandle = row.cells[col].childNodes[0].value
oldselectedCells = selectedCellsFld.value + datatableOnLoadDivider;
left = selItemHandle.indexOf("=");
right = selItemHandle.length;
selRightItemHandle = selItemHandle.substring(left+1,right);
var index=getColumnIndex(tBody,"Name");
if(index!=null)
{
if(field == 1)
{
window.opener.document.TemplateForm.eds_asbactionscfg_item_handle_child_physpart.value = selRightItemHandle;
window.opener.document.TemplateForm.ChildPhysicalPart.value = row.cells[index].childNodes[0].innerHTML;
}
else if (field == 2)
{
window.opener.document.TemplateForm.eds_asbactionscfg_dev_doc_item_handle_name.value = selRightItemHandle;
window.opener.document.TemplateForm.DeviationObject.value = row.cells[index].childNodes[0].innerHTML;
}
else if (field == 3)
{
window.opener.document.TemplateForm.eds_asbactionscfg_dev_doc_item_handle_name.value = selRightItemHandle;
window.opener.document.TemplateForm.DeviationObject.value = row.cells[index].childNodes[0].innerHTML;
}
}
}
}
window.close();
}
JS Code:-
function getColumnIndex(tBody,columnName)
{
var cells = tBody.parentNode.getElementsByTagName('th');
for (var i=0;i<cells.length; i++)
{
if(cells[i].hasChildNodes())
{
if(cells[i].childNodes[0].innerHTML.replace(/(\r\n|\n|\r)/gm ,"").trim() == columnName)
{
return i;
}
}
}
}
i had debug this code with firebug & calling getColumnIndex(tBody,columnName) function works fine but when it return to caller the var index=getColumnIndex(tBody,"Name"); the index value is "undefine".
suggest some solution.
getColumnIndex(tBody,columnName) function works fine.
as if it matches this if condition
if(cells[i].childNodes[0].innerHTML.replace(/(\r\n|\n|\r)/gm ,"").trim() == columnName)
{
return i;
}
so that it returns something.
but when you replace this
var index=getColumnIndex(tBody,"Name"); so that coulmnName would be "Name" in String.
And it doesn't match with any columnName so that your condition going to be wrong and function doesn't return anything.
var index=getColumnIndex(tBody,"Name"); the index value is "undefine".
suggestion is put some else condition on that and return some error message like this :
if(cells[i].childNodes[0].innerHTML.replace(/(\r\n|\n|\r)/gm ,"").trim() == columnName)
{
return i;
} else{
// put some error message
// return null
}
i had debug this code with firebug & calling getColumnIndex(tBody,columnName) function works fine
From this, I'm assuming that there isn't anything wrong with the implementation of your getColumnIndex function, so your issue with getting an undefined value must have to do with when this function is returning a value.
but when it return to caller the var index=getColumnIndex(tBody,"Name"); the index value is "undefine".
This leads me to assume that your tBody variable is not being set correctly, given that the "function works fine".
I'm assuming there is a case in your code where the conditions of your getColumnIndex function is not met.
function getColumnIndex(tBody,columnName)
{
var cells = tBody.parentNode.getElementsByTagName('th');
for (var i=0;i<cells.length; i++)
{
if(cells[i].hasChildNodes())
{
if(cells[i].childNodes[0].innerHTML.replace(/(\r\n|\n|\r)/gm ,"").trim() == columnName)
{
return i;
}
}
}
// If your code reaches this point, then the prior conditions have not been met
// You can choose to do something else here for return false/undefined etc.
return undefined;
}
I need to consume a SOAP web service which, naturally, sends its response in XML, since I'm developing a Appcelerator Titanium mobile app I would prefer the response in JSON. After looking online I converted the response using this Javascript code, it mostly worked but returned results such as the following:
{
"SOAP-ENV:Body" : {
"ns1:linkAppResponse" : {
"ns1:result" : {
#text : true;
};
"ns1:uuid" : {
#text : "a3dd915e-b4e4-43e0-a0e7-3c270e5e7aae";
};
};
};
}
Of course the colons and hashes in the caused problems so I adjusted the code to do a substring on the name and drop off anything before the ':', then a stringified the resulting JSON, removed all the hashes and parsed the JSON again. This is a bit messy for my liking but I end up with something usable.
Here is the xmlToJson code I'm using:
// Changes XML to JSON
function xmlToJson(xml) {
// Create the return object
var obj = {};
if (xml.nodeType == 1) {// element
// do attributes
if (xml.attributes.length > 0) {
obj["#attributes"] = {};
for (var j = 0; j < xml.attributes.length; j++) {
var attribute = xml.attributes.item(j);
obj["#attributes"][attribute.nodeName] = attribute.nodeValue;
}
}
} else if (xml.nodeType == 3) {// text
obj = xml.nodeValue;
}
// do children
if (xml.hasChildNodes()) {
for (var i = 0; i < xml.childNodes.length; i++) {
var item = xml.childNodes.item(i);
var nodeName = item.nodeName.substring(item.nodeName.indexOf(":") + 1);
if ( typeof (obj[nodeName]) == "undefined") {
obj[nodeName] = xmlToJson(item);
} else {
if ( typeof (obj[nodeName].push) == "undefined") {
var old = obj[nodeName];
obj[nodeName] = [];
obj[nodeName].push(old);
}
obj[nodeName].push(xmlToJson(item));
}
}
}
return obj;
};
module.exports = xmlToJson;
Which results in the following JSON:
{
Body : {
linkAppResponse : {
result : {
text : true;
};
uuid : {
text : "9022d249-ea8a-47a3-883c-0f4cfc9d6494";
};
};
};
}
While this returns a JSON object I can use, I would prefer to have the resulting JSON in the following form:
{
result : true;
uuid : "9022d249-ea8a-47a3-883c-0f4cfc9d6494";
};
Mostly so it's less verbose and I can simply call json.result in order check if the query was successful instead of json.Body.linkAppResponse.result.text
Any help is greatly appreciated.
Came up with a working solution, not any less dirty but it works and returns data in the format I want.
function soapResponseToJson(xml) {
var json = xmlToJson(xml).Body;
console.debug(json);
var response = {};
for (var outterKey in json) {
if (json.hasOwnProperty(outterKey)) {
temp = json[outterKey];
for (var innerKey in temp) {
if (temp.hasOwnProperty(innerKey)) {
response[innerKey] = temp[innerKey].text;
}
}
}
}
console.debug(response);
return response;
}
// Changes XML to JSON
function xmlToJson(xml) {
// Create the return object
var obj = {};
if (xml.nodeType == 1) {// element
// do attributes
if (xml.attributes.length > 0) {
obj["#attributes"] = {};
for (var j = 0; j < xml.attributes.length; j++) {
var attribute = xml.attributes.item(j);
obj["#attributes"][attribute.nodeName] = attribute.nodeValue;
}
}
} else if (xml.nodeType == 3) {// text
obj = xml.nodeValue;
}
// do children
if (xml.hasChildNodes()) {
for (var i = 0; i < xml.childNodes.length; i++) {
var item = xml.childNodes.item(i);
var nodeName = item.nodeName.substring(item.nodeName.indexOf(":") + 1).replace('#', '');
if ( typeof (obj[nodeName]) == "undefined") {
obj[nodeName] = xmlToJson(item);
} else {
if ( typeof (obj[nodeName].push) == "undefined") {
var old = obj[nodeName];
obj[nodeName] = [];
obj[nodeName].push(old);
}
obj[nodeName].push(xmlToJson(item));
}
}
}
return obj;
};
module.exports = soapResponseToJson;
console.debug(json):
{
linkAppResponse : {
result : {
text : true;
};
uuid : {
text : "e4f78c5f-1bc2-4b50-a749-19d733b9be3f";
};
};
}
console.debug(response):
{
result : true;
uuid : "e4f78c5f-1bc2-4b50-a749-19d733b9be3f";
}
I'm going to leave this question open for a while in case someone comes up with a better solution.
I feel like this is a fairly ugly solution (hope it doesn't offend you :) ).
Why don't you marshal the xml to an object and then use gson or jackson to map to json.
I don't know what framework you use, in spring for example, you can use jaxb2 to marshal and jackson or gson to transform your object to json.