I am fairly certain this is a ten penny closure question. But having read a few articles on closures, I still cannot get this to work.
character is always returned as 'Z'. character is also a global variable.
I need "render" to remember the character in the loop:
populateList: function()
{
var render = function(tx, result)
{
console.log(character);
for (var i = 0; i < result.rows.length; i++)
{
var contact = result.rows.item(i);
console.log(contact.Name);
}
}
var str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
for(var i = 0; i < str.length; i++)
{
var nextChar = str.charAt(i);
database.open();
var sql = "SELECT Name FROM Contact WHERE Name LIKE \'" + nextChar + "%\' ORDER BY Name";
database.query(sql, render);
}
}
var render = function(character)
{
return function(tx, result)
{
console.log(character);
for (var i = 0; i < result.rows.length; i++)
{
var contact = result.rows.item(i);
console.log(contact.Name);
}
}
}
Usage:
database.query(sql, render(nextChar));
Edit:
Also, asawyer is correct in his comment above -- assuming you are using node-mysql, it has support for parameterized queries:
database.query("SELECT * FROM foo WHERE bar = ?", [ 1 ]);
Use that and save yourself some trouble!
Untested:
populateList: function()
{
var render = function(char)
{
console.log(char);
return function(tx, result) {
for (var i = 0; i < result.rows.length; i++)
{
var contact = result.rows.item(i);
console.log(contact.Name);
}
};
}
var str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
for(var i = 0; i < str.length; i++)
{
var nextChar = str.charAt(i);
database.open();
var sql = "SELECT Name FROM Contact WHERE Name LIKE \'" + nextChar + "%\' ORDER BY Name";
database.query(sql, render(nextChar));
}
}
Use an immediately executing function that returns a function that calls render with the parameters:
database.query(sql, (function(nextChar) {
return function(tx, result) {
return render(tx, result, nextChar);
};
})(nextChar));
Then add the appropriate nextChar parameter to render, too.
var render = function(tx, result)
{
console.log(character);
***var char = character;***
for (var i = 0; i < result.rows.length; i++)
{
var contact = result.rows.item(i);
***console.log(char);***
console.log(contact.Name);
}
}
i guess this is what you need. add the highlighted lines. cheers
Related
I'm brand new to JS and am trying to build a template function (assignment in a MOOC) that basically returns a function that returns the rendered template based on an input string and delimiter.
Anyway, this is the code that I have so far and I have no idea why it is breaking.. I've really tried everything that I can think of!
var template = function(stringToParse, options) {
// find out if custom delimiters are being used
if (typeof options != 'undefined') {
var openDelim = options.open;
var closeDelim = options.close;
} else {
var openDelim = '*(';
var closeDelim = ')*';
}
// get the length of the closing delim for parsing later
var delimCharLen = closeDelim.length;
// helper function
function parseOutFiller(_array) {
// get an array of the indices of each closing delim in the string
var closingDelims = [];
for (i=0; i < _array.length; i++) {
closingDelims.push(_array[i].indexOf(closeDelim));
}
// remove the filler text leading up to the closing dim in each substring
for (i = 0; i < _array.length; i++) {
if (closingDelims[i] > 0) {
_array[i] = _array[i].slice(closingDelims[i] + delimCharLen)
}
}
return _array
}
// split array, get the closing indices, and parse out the filler text
var splitArray = stringToParse.split(openDelim);
var parsedString = parseOutFiller(splitArray);
return new Function("var locParsedString = [" + parsedString + "];\
var inputCopy = [];\
for (i=0; i < arguments.length-1; i++) {\
inputCopy.push(arguments[i])\
}\
var templateString = '';\
for (i=0; i < inputCopy.length; i++) {\
templateString += locParsedString[i];\
templateString += inputCopy[i];\
}\
templateString += locParsedString[locParsedString.length-1];\
nRepeat = arguments[arguments.length-1];\
for (i=0; i < nRepeat; i++) {\
console.log(templateString);\
}"
)
}
Then when I run it...
var string = "Is <<! thing !>> healthy to <<! action !>>?";
var logResult = template(string, {open: '<<!', close: '!>>'});
logResult('this', 'eat', 3)
/*
Which should print:
"Is this healthy to eat?"
"Is this healthy to eat?"
"Is this healthy to eat?"
*/
Thanks in advance!
Instead of using new Function(), just use return function () { }.
That way, there is no need to create locParserString inside the function. You can use parsedString directly:
var template = function(stringToParse, options) {
// find out if custom delimiters are being used
if (typeof options != 'undefined') {
var openDelim = options.open;
var closeDelim = options.close;
} else {
var openDelim = '*(';
var closeDelim = ')*';
}
// get the length of the closing delim for parsing later
var delimCharLen = closeDelim.length;
// helper function
function parseOutFiller(_array) {
// get an array of the indices of each closing delim in the string
var closingDelims = [];
for (i=0; i < _array.length; i++) {
closingDelims.push(_array[i].indexOf(closeDelim));
}
// remove the filler text leading up to the closing dim in each substring
for (i = 0; i < _array.length; i++) {
if (closingDelims[i] > 0) {
_array[i] = _array[i].slice(closingDelims[i] + delimCharLen)
}
}
return _array
}
// split array, get the closing indices, and parse out the filler text
var splitArray = stringToParse.split(openDelim);
var parsedString = parseOutFiller(splitArray);
return function () {
var inputCopy = [];
for (i=0; i < arguments.length-1; i++) {
inputCopy.push(arguments[i])
}
var templateString = '';
for (i=0; i < inputCopy.length; i++) {
templateString += parsedString[i];
templateString += inputCopy[i];
}
templateString += parsedString[parsedString.length-1];
nRepeat = arguments[arguments.length-1];
for (i=0; i < nRepeat; i++) {
console.log(templateString);
}
};
}
I've created a JavaScript object to get the number of times a character repeats in a string:
function getFrequency(string) {
// var newValsArray =[];
var freq = {};
for (var i=0; i<string.length;i++) {
var character = string.charAt(i);
if (freq[character]) {
freq[character]++;
} else {
freq[character] = 1;
}
}
return freq;
}
Now, I'm trying to construct a new string composed of the keys & their properties (the letters) & numbers of times the letters repeat if the number (property) is more than one but I keep getting undefined and I don't know why:
function newString(freq){
var newValsArray = [];
for (var prop in freq) {
if (freq[prop]>1){
newValsArray.push(prop + freq[prop]);
}
else if (freq[prop] < 2){
newValsArray.push(prop);
}
}
return newValsArray;
}
I feel like my syntax is off or something... if anyone has any suggestions, I'd really appreciate it...
You aren't explicitly returning anything from newString(), so it will return undefined. It sounds like you want something like this:
return newValsArray.join('');
at the end of newString() to construct an actual string (instead of returning an array). With that change, newString(getFrequency("Hello there") will return 'He3l2o thr'.
function getFrequency(string) {
// var newValsArray =[];
var freq = {};
for (var i = 0; i < string.length; i++) {
var character = string.charAt(i);
if (freq[character]) {
freq[character] ++;
} else {
freq[character] = 1;
}
}
return freq;
}
function newString(freq) {
var newValsArray = [];
for (var prop in freq) {
if (freq[prop] > 1) {
newValsArray.push(prop + freq[prop]);
} else if (freq[prop] < 2) {
newValsArray.push(prop);
}
}
return newValsArray.join("");
}
var mystring = "Here are some letters to see if we have any freq matches and so on.";
var results = newString(getFrequency(mystring));
var elem = document.getElementById("results");
elem.innerHTML = results;
<div id="results"></div>
You are not returning anything from the newString function. Add return newString; as the last line of the newString function. Adding that line does result in something being returned, though I can't tell if it is what you expected.
var text = "asdfjhwqe fj asdj qwe hlsad f jasdfj asdf alhwe sajfdhsadfjhwejr";
var myFreq = getFrequency(text);
show(myFreq);
var myNewValsArray = newString(myFreq);
show(myNewValsArray);
function getFrequency(string) {
// var newValsArray =[];
var freq = {};
for (var i=0; i<string.length;i++) {
var character = string.charAt(i);
if (freq[character]) {
freq[character]++;
} else {
freq[character] = 1;
}
}
return freq;
}
function newString(freq){
var newValsArray = [];
for (var prop in freq) {
if (freq[prop]>1){
newValsArray.push(prop + freq[prop]);
}
else if (freq[prop] < 2){
newValsArray.push(prop);
}
}
return newValsArray; // ******** ADD THIS LINE
}
function show(msg) {
document.write("<pre>" + JSON.stringify(msg, null, 2) + "</pre>");
}
I have a question. When querying my Json object, although i have my Field as same name and all Json rows available give me an error that is undefined.
//e.g: row.DepParentId
Bellow is my code. Am I missing some tag?
function convert(rows) {
debugger;
function exists(rows, parent) {
for (var i = 0; i < rows.length; i++) {
if (rows[i].DepId === parent) return true;
}
return false;
}
var nodes = [];
// get the top level nodes
for (var i = 0; i < rows.length; i++) {
var row = rows[i];
if (!exists(rows, row.DepParentId)) {
nodes.push({
id: row.DepId,
name: row.Title
});
}
}
var toDo = [];
for (var i = 0; i < nodes.length; i++) {
toDo.push(nodes[i]);
}
while (toDo.length) {
var node = toDo.shift();
// the parent node
// get the children nodes
for (var i = 0; i < rows.length; i++) {
var row = rows[i];
if (row.DepParentId == node.Id) {
var child = {
Id: row.DepId,
Name: row.Title
};
if (node.options) {
node.options.push(child);
} else {
node.options = [child];
}
toDo.push(child);
}
}
}
return nodes;
}
My Json example for one row picked from Firefox
"{"DepId":7,"DepParentId":3,"Title":"OTT"}"
Thanks for helping
Joao
thanks all for helping, it's working now, the problem was the JSON.stringify() was returning only an [Object] so when you use JSON.parse() generates a sintax error.
function onLoaded() {
var itemsCount = items.get_count();
for (var i = 0; i < itemsCount; i++) {
var item = items.itemAt(i);
var dep = JSON.stringify(item.get_fieldValues());
deps.push(dep);
}
So, i had to change the format to be valid to parse like this
var dt = "[" + deps + "]";
var ret = JSON.parse(dt);
Thanks
Joao
I need to sort list strings under the table ,so for that i have written following lines of code but on console i am not getting any values:
var j = 9;
var rows = element.all(by.repeater('row in renderedRows'));
var column = element.all(by.repeater('col in renderedColumns'));
expect(rows.count()).toEqual(5); //here its printing number of rows
expect(column.count()).toEqual(5); //here its printing number of columns
var arr = [rows.count()];
for (var i = 0; i < rows.count(); i++) {
console.log("aai" + i);
if (i = 0) {
//var columnvalue=column.get(9).getText();
var columnvalue = column.get(9).getText().then(function(ss) {
return ss.trim();
arr[i] = ss.trim(); //here it will save the value first value of column
console.log("value1" + arr[i]);
expect(arr[i]).toEqual('DN');
console.log("aa" + ss.trim());
});
} else {
var j = j + 8;
var columnvalue = column.get(j).getText().then(function(ss) {
return ss.trim();
arr[i] = ss.trim(); //here it will save the other values of column
console.log("value" + arr[i]);
expect(arr[i]).toEqual('DN');
console.log("ab" + ss.trim());
});
}
}
Sorting_Under_Table: function(col){
test = [];
var m;
var dm = 0;
element(by.xpath('//div[#class="ngHeaderScroller"]/div['+col+']')).click();
element.all(by.repeater('row in renderedRows')).then(function(row) {
m = row.length;
for (i = 1; i <= row.length; i++)
{
user_admin_table_name = browser.driver.findElement(by.xpath('//div[#class="ngCanvas"]/div['+i+']/div['+col+']'));
user_admin_table_name.getText().then(function(text) {
var test_var1 = text.toLowerCase().trim();
test.push(test_var1);
var k = test.length
if (k == m){
for (j = 0; j < test.length; j++){
test.sort();
d=j+1;
user_admin_table_name1 = browser.driver.findElement(by.xpath('//div[#class="ngCanvas"]/div['+d+']/div['+col+']'));
user_admin_table_name1.getText().then(function(text1) {
var test_var2 = text1.toLowerCase().trim();
if (test_var2 == test[dm]){
expect(test_var2).toEqual(test[dm]);
dm = dm +1;
}else {
expect(test_var2).toEqual(test[dm]);
log.error("Sorting is not successful");
dm = dm +1;
}
});
}
}
});
}
});
},
You can use this code for sorting and verifying is it sorted or not
I'm not sure how your above example is doing any sorting, but here's a general solution for trimming and then sorting:
var elementsWithTextToSort = element.all(by.xyz...);
elementsWithTextToSort.map(function(elem) {
return elem.getText().then(function(text) {
return text.trim();
});
}).then(function(trimmedTexts) {
return trimmedTexts.sort();
}).then(function(sortedTrimmedTexts) {
//do something with the sorted trimmed texts
});
http://jsfiddle.net/84nv2dmL/
I'm trying to get these images of letters to display in order. I tried creating divs dynamically and filling them with the img, but that didn't work. How can I get these letters to display in order?
jsfiddle code:
function getQueryStringVar(name){
var qs = window.location.search.slice(1);
var props = qs.split("&");
for (var i=0 ; i < props.length;i++){
var pair = props[i].split("=");
if(pair[0] === name) {
return decodeURIComponent(pair[1]);
}
}
}
function getLetterImage(tag){
var flickerAPI = "https://www.flickr.com/services/feeds/photos_public.gne?jsoncallback=?";
return $.getJSON( flickerAPI, {
tags: tag,
tagmode: "all",
format: "json"
})
.then(function (flickrdata) {
//console.log(flickrdata);
var i = Math.floor(Math.random() * flickrdata.items.length);
var item = flickrdata.items[i];
var url = item.media.m;
return url;
});
}
$(document).ready(function() {
var name = getQueryStringVar("name") || "Derek";
var str = "letter,";
var searchtags = new Array()
for (var i = 0; i < name.length; i++) {
//console.log(str.concat(searchtags.charAt(i)));
searchtags[i] = str.concat(name.charAt(i));
}
for (var j = 0; j < name.length; j++){
var request = getLetterImage(searchtags[j]);
request.done(function(url) {
$("body").append("<img src="+ url + "></img>");
//var ele = document.createElement("div");
//ele.setAttribute("class", "img" + j--);
//document.body.appendChild(ele);
//$("<img src="+ url +"></img>").appendTo("img"+j);
});
}
//$("#img"+i).html("<img src="+ url + "></img>");
});
You basically need to keep track of the order that you are appending your images to the DOM, and make sure that they are in sync with the letters in the name. Created a fiddle with a fix. Comments are in line:
http://jsfiddle.net/84nv2dmL/2/
function getQueryStringVar(name) {
var qs = window.location.search.slice(1);
var props = qs.split("&");
for (var i = 0; i < props.length; i++) {
var pair = props[i].split("=");
if (pair[0] === name) {
return decodeURIComponent(pair[1]);
}
}
}
function getLetterImage(tag) {
var flickerAPI = "https://www.flickr.com/services/feeds/photos_public.gne?jsoncallback=?";
return $.getJSON(flickerAPI, {
tags: tag.char,
tagmode: "all",
format: "json"
})
.then(function(flickrdata) {
//console.log(flickrdata);
var i = Math.floor(Math.random() * flickrdata.items.length);
var item = flickrdata.items[i];
var url = item.media.m;
// return an object with url AND index
return {
ind: tag.ind,
img: url
};
});
}
$(document).ready(function() {
var name = getQueryStringVar("name") || "Derek";
var urls = new Array(name.length); // array or URLs, in correct order
var urlCounter = []; // keeps count or URLs received
var str = "letter,";
var searchtags = new Array();
for (var i = 0; i < name.length; i++) {
searchtags[i] = {
char: str.concat(name.charAt(i)),
ind: i
};
}
for (var j = 0; j < name.length; j++) {
var request = getLetterImage(searchtags[j]);
request.done(function(url) {
// when request is done, place image url in 'urls' array, in the correct order
urls[url.ind] = url.img;
// push object to the counter array, just to keep count
urlCounter.push(url);
// check if all image urls have been collected
checkComplete();
});
}
function checkComplete() {
// if the number of URLs received is equal
// to the number of characters in the name
// append the images from the ordered array
if (urlCounter.length == name.length) {
for (var k = 0; k < urls.length; k++) {
$("body").append("<img src=" + urls[k] + "></img>");
}
}
}
});
$("#div_id").append("<img src="+ url + "></img>");
Here div_id is the id you gave to the div.
Append adds img tag with source src to it.
Please give the html code too along with the script to help understand the problem better