onlogerror event in testcomplete - javascript

I have a function which compares 2 array values. As soon as a mismatch value is found the execution stops , but
i want to only when all comparison have been done and if error has been found. There is OnLogError in testcomplete but
do not know how to use it
function compare() {
for (var i = 0; i < arrActualIntendedVal.length; i++) {
if (val1[i] != val2[i]) {
Log.Error("Value " + val1[intArrIndex] + " do not match to Actual Value " +
val2[intArrIndex]);
Runner.Stop(0);
}
}
return true;
}

You just need to "remember" that there was an error and post the corresponding info after your loop is finished.
function compare() {
var errors = new Array();
for (var i = 0; i < arrActualIntendedVal.length; i++) {
if (val1[i] != val2[i]) {
errors.push("Value " + val1[intArrIndex] + " do not match to Actual Value " + val2[intArrIndex]);
}
}
if (errors.length > 0) {
Log.Error("Error when comparing arrays", errors.join("\r\n"));
Runner.Stop();
}
return true;
}

Related

Need JavaScript example for fetch() etc

I want to learn such new JavaScript features as fetch() and arrow functions. To this end, I selected a function from a recent app, and attempted to replace older features with new. Very little success. Here's my original function:
function popNames(arNumbers,ctrlName) {
var arSortedList = [];
var strNameList = "";
$.getJSON("NAME.json").done(function(zdata) {
$.each(arNumbers, function(i, ydata) {
$.each(zdata.NAME, function(k,v) {
if(v.idName == ydata) {// important: === did NOT work
if(ctrlName) arSortedList.push(v.last + ", " + v.first + ";" + v.idName);
else arSortedList.push(v.last + ", " + v.first);
}
}); // each element of NAME.json
}); // each idName value in the array passed
if(ctrlName) {
setOptions(arSortedList, ctrlName);
} else {
strNameList = arSortedList.join();
}
}); // getJSON NAME
}
I was successful using this line:
fetch("NAME.json").then(zdata => zdata.json())
but nothing I did after that worked. I'd appreciate seeing an example from which I can learn.
function popNames(arNumbers,ctrlName) {
let arSortedList = [];
let strNameList = "";
fetch("NAME.json").then(zdata => zdata.json())
.then(zdata => {
for(const ydata of arNumbers) {
for(const v of zdata.NAME) {
if(v.idName == ydata) { // important: === did NOT work
if(ctrlName) arSortedList.push(v.last + ", " + v.first + ";" + v.idName);
else arSortedList.push(v.last + ", " + v.first);
}
}
}
if(ctrlName) {
setOptions(arSortedList, ctrlName);
} else {
strNameList = arSortedList.join();
}
}); // getJSON NAME
}
I was researching why I couldn't next two Array.forEach statements, and discovered a new iterable construction (for...of).

Storing my game score in local storage

I'm pretty new to JS so I'm struggling here. Basically I have a score function in place in my JavaScript and I want to store this locally so it can be retrieved by another page at a later time. I used local storage for my login and register page, but I'm not sure how I can do the same for score.
add_row_of_pipes: function() {
var hole = Math.floor(Math.random()*5)+1;
for (var i = 0; i < 8; i++)
if (i != hole && i != hole +1)
this.add_one_pipe(400, i*60+10);
this.score += 1;
this.label_score.content = this.score;
};
All feedback will be highly appreciated:)
This is how you can store and retrieve values from localStorage:
// Store
localStorage.setItem("score", "100");
// Retrieve
var score = localStorage.getItem("score");
This is a small LocalStorage framework that i've put together.
It covers all of the obvious functionality you would want from localstorage.
function set_LocalStorage(key,value)
{
//localStorage.setItem("name of variable", "value to store");
localStorage.setItem(key, value);
console.log('LocalStorage: ' + key + ' has been set to: ' + value);
}//End set_LocalStorage
function get_LocalStorage(key)
{
return localStorage.getItem(key);
console.log('LocalStorage: ' + key + ' has a value of: ' + value);
}//End get_LocalStorage
function remove_LocalStorage(key)
{
localStorage.removeItem(key);
console.log('LocalStorage: ' + key + ' has been removed');
}//End remove_LocalStorage
function check_LocalStorage_exist(key)
{
var v = get_LocalStorage(key);
var v2 = toInteger(v);
var FeedBack;
if(v2 == 'null' || v2 === 'NaN' || v2 == 'undefined' || v2 == ''){ /*console.log('key '+key+' does NOT exist');*/ FeedBack='NO';}
if(v2!=0){
console.log('key '+key+' exist');
FeedBack='YES';
}
return FeedBack;
}//End check_LocalStorage
function list_All_LocalStorage()
{
for (var i = 0; i < localStorage.length; i++)
{
let item = localStorage.getItem(localStorage.key(i)); //--Will only need to have this on when collecting APP_DATA
console.log('------ LocalStorage: '+localStorage.key(i)+' = '+item);
}
}//End list_All_LocalStorage
function remove_All_LocalStorage()
{
for (var i = 0; i < localStorage.length; i++)
{
let s_key = localStorage.key(i);
remove_LocalStorage(s_key);
}
}//End remove_All_LocalStorage
You're welcome! :)

How do I turn this into a callback function?

I'm new to Javascript, and callbacks are blowing my mind a little at the moment. How do I turn the teletyperDiologue function into a callback? The main reason is I want the teletyper to finish it's job before the displayOut function finishes. Thank you in advance for your help.
function displayOut() {
// images
document.getElementById("imgBox").style.backgroundImage = "url(" + db.rooms[roomLoc].roomImg + ")";
// Diologue box
diologueBox.innerHTML = ""; // Clear Box
teleTyperDiologue(db.rooms[roomLoc].description +
" The room contains: " +
(function() {
let x = "";
for (let i = 0; i < db.items.length; i++) {
if (db.items[i].location === roomLoc && db.items[i].hidden === false) {
x += db.items[i].name + ", "
}
}
x = x.slice(0, x.length -2);
if (x === "") {
x = " nothing of special interest";
}
return x;
})()
+ ".");
};
// Teletyper for Diologue Box
function teleTyperDiologue(string) {
for (let i = 0; i < string.length; i++) {
setTimeout(function() {
diologueBox.innerHTML += string.slice(i, i + 1);
}, 5 * i);
}
}
As an example:
function test(a) { a(); }
function x() { alert('hello'); }
test(x);
in your case:
function displayOut(callback) {
// images
document.getElementById("imgBox").style.backgroundImage = "url(" + db.rooms[roomLoc].roomImg + ")";
// Diologue box
diologueBox.innerHTML = ""; // Clear Box
callback(db.rooms[roomLoc].description +
" The room contains: " +
(function() {
let x = "";
for (let i = 0; i < db.items.length; i++) {
if (db.items[i].location === roomLoc && db.items[i].hidden === false) {
x += db.items[i].name + ", "
}
}
x = x.slice(0, x.length -2);
if (x === "") {
x = " nothing of special interest";
}
return x;
})()
+ ".");
};
displayOut(teleTyperDiologue);
You can pass functions around like variables and return them in functions and use them in other functions. So, when you pass a callback function as an argument to another function, you only need to pass the function definition.
See example below.
function displayOut() {
console.log("Display Out running...");
}
function teleTyperDiologue(stringParam, callback) {
console.log("Running teleTyper with string param passed of: ", stringParam);
callback();
}
teleTyperDiologue ("Test string", displayOut);

Javascript program keeps outputting wrong index of array

I'm trying to finish an assignment, I'm stuck at and can't find a solution.
Below is my full code.
//Student Object
var student = {
f_name: "",
l_name: "",
s_numb: "",
email: "",
courses: [],
/*This function returns if current object has a specific course
and returns true if it does and false if not.*/
hasCourse: function (course) {
for (var c = 0; c < this.courses.length; c++) {
if (course == this.courses[c]) {
return true;
}
}
return false;
}
};
/*This function returns name with first letter
capitalized and the rest lowercase.*/
function formatingName(name) {
return name.charAt(0).toUpperCase() + name.substr(1, name.length);
}
/*This function validates to match the Student ID pattern and
returns true it matches and false if not.*/
function validateStudentID(sid) {
var patt = /^([0-9]{3}[.]){2}[0-9]{3}$/;
return patt.test(sid);
}
/*This function receives a string array of course codes which
are to be registered for a student. The function returns an empty
string indicating all course codes in the array are valid; otherwise
the function returns the first invalid course code in the array.*/
function validateCourses(courses) {
var error = false;
for (i = 0; i < courses.length; i++) {
if (error == false) {
if (courses[i] != "APC100" && courses[i] != "IPC144" &&
courses[i] != "ULI101" && courses[i] != "IOS110" &&
courses[i] != "EAC150" && courses[i] != "IBC233" &&
courses[i] != "OOP244" && courses[i] != "DBS201" &&
courses[i] != "INT222") {
error = courses[i];
break;
}
}
}
if (error != false) {return error;} else {return "";}
return '';
}
var response = true; //Continues to prompt if error is true
var error = false; //Error flag
var temp_obj = []; //Temporary object that hold current object's values
var temp_course = [];
var students = [];
var x = 0;
while (response == true) {
do {
var str = prompt("Please enter first name, last name, student ID,\nemail and courses (separated by ',')");
if (str == "" || str === null) {
response = false;
break;
}
//Removing white spaces in the string
str = str.split(' ').join('');
//Splitting the string into array by , (coma) and assigning it to temporary object array
temp_obj = str.split(',');
//Validating Student ID
if (validateStudentID(temp_obj[2]) == false) {
alert(temp_obj[2] + " is not a valid student ID, Please use xxx.xxx.xxx format.\nPlease try again!");
error = true;
}
//Validating if student is registered in atleast 1 course.
if (temp_obj.length < 5) {
alert("A student must be registered in at-least 1 course");
error = true;
}
//Checking if student is registered in more than 6 courses
if (temp_obj.length > 10) {
temp_obj = temp_obj.slice(0,9);
}
//Extracting courses from temporary object array
temp_course = temp_obj.slice(4, temp_obj.length);
//Makking all the courses uppercase
for (i = 0; i < temp_course.length; i++) {
temp_course[i] = temp_course[i].toUpperCase();
}
//Validating if courses are valid
if (validateCourses(temp_course) != "") {
alert(validateCourses(temp_course) + " is not the course provided by CPD program!\nPlease try again.");
error = true;
}
}
while (error == true);
//Break out of loop if user submitted nothing or if user pressed cancel
if (response == false) {break;}
//Merging cources array back with temporary object array
temp_obj = temp_obj.concat(temp_course);
//Creating a new instance of a student
students[x] = Object.create(student);
//Assigning values to student object from temporary object;
students[x].f_name = formatingName(temp_obj[0]); //Formatting name
students[x].l_name = formatingName(temp_obj[1]);
students[x].s_numb = temp_obj[2];
students[x].email = temp_obj[3].toLowerCase(); //Making the email all lowercase
//Making the course codes in Uppercase
for (i = 0; i < (temp_obj.length) - 4; i++ ) {
students[x].courses[i] = temp_obj[i + 4].toUpperCase();
}
x++;
}
//Printing total registered students
alert("There are total " + students.length + " students registered.");
var R_fname = [];
var R_lname = [];
var R_sid = [];
var R_email = [];
do {
var no_error = false;
var query = true;
var query_course = [];
while (no_error == false) {
query = prompt("Please enter a course code:");
if (query == "" || query == null) {
query = false;
break;
}
no_error = true;
query_course[0] = query.toUpperCase();
if (validateCourses(query_course) != "") {
alert(query + " is not the course provided by CPD program!\nPlease try again");
no_error = false;
}
}
if (query == false) {break;}
//THIS IS WHERE I THINK THE PROBLEM IS
//THIS IS WHERE I THINK THE PROBLEM IS
//THIS IS WHERE I THINK THE PROBLEM IS
//THIS IS WHERE I THINK THE PROBLEM IS
for (var a = 0; a < students.length; a++) {
//Checking if student is registred in a course
if (students[a].hasCourse(query_course) == true) {
//Assigning values to temporary array.
R_fname[a] = students[a].f_name;
R_lname[a] = students[a].l_name;
R_sid[a] = students[a].s_numb;
R_email[a] = students[a].email;
}
}
var fin_str = "";
//Concatenating all the students in a specific course to fin_str as string.
for (var b = 0; b < R_fname.length; b++) {
fin_str += (R_fname[b] + " " + R_lname[b] + " " + R_sid[b] + " " + R_email[b] + " \n");
}
//Printing list of student in a specific course
alert("List of students registered in " + query + "\n\n" + fin_str);
//Retting temporary arrays
R_fname.length = 0;
R_lname.length = 0;
R_sid.length = 0;
R_email.length = 0;
//Confirms to Exit the query loop
if (confirm("Click 'OK' to continue to query class lists.\nClick 'Cancel' to stop the program.") == false) {break;}
}
while (query != false);
These are the test values:
roy,bean,056.171.486,rbean#example.ca,int222
carl,bell,121.126.536,cbell#example.ca,dbs201,int222
eric,brand,046.123.976,ebrand#example.ca,oop244,dbs201,int222
henry, clay, 034.146.412, hclay#example.ca , ibc233 , oop244 , dbs201 , int222
When the program asks to enter the course code; it is suppose to see if the students have that course and only if they do, it prints that students info.
In my case, even if student does not have the course it still prints it.
Please run the code to see if it makes more sense... I can't explain any better
The problem can be reduced to this:
var Foo = {
courses: []
};
var x = Object.create(Foo);
var y = Object.create(Foo);
x.courses.push(123);
alert(y.courses[0]); // "123"
The reason for this behaviour is that both objects inherit the same prototype and any changes made to .courses will apply to both objects.
For this reason, it would be better to create a constructor function instead:
function Foo()
{
this.courses = [];
}
var x = new Foo();

Combine objects in 2 different arrays javascript

I have 2 javascript requests that give back results in an array of objects.
The first object looks like this:
[Object {user_id="6", meta_value="5", user_nicename="richbai90", more...},
Object {user_id="7", meta_value="1", user_nicename="testing123", more...}]
the 2nd looks like this
[Object { usr="6", score="1 / 1", quiz_id="1"},
Object { usr="7", score="1 / 1", quiz_id="1"},
Object { usr="7", score="1/5", quiz_id="3"}]
Array 2 is the details of array one
What I need is a way to relate these together in javascript so that I can put the information from object 2 in the document where it needs to correspond with the information from object one. The easiest way I could think to do this would be to combine the arrays where the user ids were the same but this appears to be more difficult then I first thought. Here was my initial approach:
$.post(AjaxRequest.ajaxurl, {
action: "get_data"
})
.done(function (json) {
console.log(json);
var data = json;
for (var i = 0; i < json.length; i++) {
if (AjaxRequest.user_ID == json[i].user_id && json[i].Quizes == "1") {
$("#result_list").append("you have taken " + json[i].Quizes + " quiz");
} else if (AjaxRequest.user_id == json[i].user_id && json[i].Quizes != "1") {
$("#result_list").append("you have taken " + json[i].Quizes + " quizzes");
} else {
$("#result_list").append(json[i].user_nicename + " has taken " + json[i].Quizes + " quizzes" + "<br>");
}
}
getDetails(json);
})
.fail(function (jqxhr, textStatus, error) {
var err = textStatus + ', ' + error;
console.log('1st Request Failed: ' + err);
});
function getDetails(data) {
$.post(AjaxRequest.ajaxurl, {
action: "get_details"
})
.done(function (details) {
console.log(data);
console.log(details);
for (var i = 0; i < data.length; i++) {
for (var i2 = 0; i2 < details.length; i++) {
while (details[i2].usr == data[i].user_id) {
console.log(details[i2]);
break;
}
}
}
$("#loading").fadeOut('fast', function () {
$("#result_list").fadeIn('fast');
});
})
.fail(function (jqxhr, textStatus, error) {
var err = textStatus + ', ' + error;
console.log('2nd Request Failed: ' + err);
});
}
In this code block is where the work is happening
for (var i = 0; i < data.length; i++) {
for (var i2 = 0; i2 < details.length; i++) {
while (details[i2].usr == data[i].user_id) {
console.log(details[i2]);
break;
}
}
}
The issue is that once the while loop breaks it doesn't seem to go to the next itteration of the for loop as I would have expected instead data[i] gets undefined. If I remove the break; then data[i] is always == details[i2] and thus crashes the browser.
Maybe I'm making it harder than it needs to be?
You could try using a 2-dimensional array.

Categories