Back to the basics of JavaScript. This is a question I am coming with is based on computation time speed of JavaScript If condition.
I have a logic which includes usage of if condition. The question is computing equal to value is faster OR not equal to value is faster?
if(vm.currentFeedbackObject.sendReminderLists[0].sendReminderFlag !== '' && vm.currentFeedbackObject.sendReminderLists[0].sendReminderedOn !== null)
{
vm.isReminderSectionVisible = true;
} else
{
vm.isReminderSectionVisible = false;
}
The above one computes not equal to
if(vm.currentFeedbackObject.sendReminderLists[0].sendReminderFlag === '' && vm.currentFeedbackObject.sendReminderLists[0].sendReminderedOn === null)
{
vm.isReminderSectionVisible = false;
} else
{
vm.isReminderSectionVisible = true;
}
The above one computes equal to value
which of both these is faster in execution?
Why don't you try it out? Write to your console this:
function notequal() {
if(vm.currentFeedbackObject.sendReminderLists[0].sendReminderFlag !== '' && vm.currentFeedbackObject.sendReminderLists[0].sendReminderedOn !== null)
vm.isReminderSectionVisible = true;
}
else {
vm.isReminderSectionVisible = false;
}
}
function yesequal() {
if(vm.currentFeedbackObject.sendReminderLists[0].sendReminderFlag === '' && vm.currentFeedbackObject.sendReminderLists[0].sendReminderedOn === null)
vm.isReminderSectionVisible = false;
}
else {
vm.isReminderSectionVisible = true;
}
}
var iterations = 1000000;
console.time('Notequal #1');
for(var i = 0; i < iterations; i++ ){
notequal();
};
console.timeEnd('Notequal #1')
console.time('Yesequal #2');
for(var i = 0; i < iterations; i++ ){
yesequal();
};
console.timeEnd('Yesequal #2')
Related
I am trying to check my user inputted password with a series of if statements and boolean variables within a function. It seems like my if statements are not modifying my boolean variables. Could someone tell me why?
I was trying to use (/[a-zA-z]/).test(pValue.charAt(0))) as a boolean to see if the first character entry was a lower or upper case letter, but that didn't work either.
document.querySelector("#enter").addEventListener("click", validate);
function validate(e) {
var count = false;
var firstChar = false;
var hasNum = false;
var special = false;
var pValue = document.querySelector("#passwrd").value;
var pLength = pValue.length;
console.log(pValue);
console.log(pLength);
if(pLength > 4 && pLength <= 8) {
count = true;
}
if(pValue.search(e.charCode === [65 - 90]) === 0) {
firstChar = true;
}
console.log(firstChar);
for(var j = 0; j < pLength; j++) {
if(pValue.charAt(j) == "$" || pValue.charAt(j) == "%" || pValue.charAt(j) == "#") {
special = true;
}
}
for(var i = 0; i < pLength; i++) {
if(!isNaN(pValue.charAt(i))) {
hasNum = true;
}
}
if(count && firstChar && hasNum && special) {
document.querySelector("#show_word").textContent = pValue;
}
}
I am trying to make a filter based on checkboxes.
The thing is js ignoring other conditions inside filter when one is active
filterData() {
return this.airlines.filter(x => {
if (this.filters.options.length != 0 || this.filters.airlines.length != 0) {
for (let i = 0; this.filters.options.length > i; i++) {
if (this.filters.options[i] == 0) {
return x.itineraries[0][0].stops == 0;
}
if (this.filters.options[i] == 1) {
return x.itineraries[0][0].segments[0].baggage_options[0].value > 0;
}
}
} else {
return x;
}
})
}
I know that return will stop the current loop, but is there any way to do it correctly?
Update-1: (When to filter record for every case checked OR case)
Replace for loop and all conditions in a single return by && for if and || condition for data:
var chbox = this.filters.options;
return $.inArray(0, chbox) != -1 && x.itineraries[0][0].stops == 0
|| $.inArray(1, chbox) != -1 && x.itineraries[0][0].segments[0].baggage_options[0].value > 0;
Hope this helps !!
$.inArray(value, arr) method will check for each checkboxes and will work for every checked ones .
Update-2 (When to filter record for every case checked AND case)
As per comment below, you are trying to use checkbox on demand so use below code:
var chbox = this.filters.options;
boolean condition = true;
if ($.inArray(0, chbox) != -1) {
conditon = conditon && x.itineraries[0][0].stops == 0;
}
if ($.inArray(1, chbox) != -1) {
conditon = conditon && x.itineraries[0][0].segments[0].baggage_options[0].value > 0;
}
return condition;
Your filter function is returning an object, which ideally should be a boolean value. Please refactor the code as below.
filterData() {
return this.airlines.filter(x => {
let result = false;
if (this.filters.options.length != 0 || this.filters.airlines.length != 0) {
for (let i = 0; this.filters.options.length > i; i++) {
if (this.filters.options[i] == 0) {
result = x.itineraries[0][0].stops == 0;
break;
} else if (this.filters.options[i] == 1) {
result = x.itineraries[0][0].segments[0].baggage_options[0].value > 0;
break;
}
}
}
return result;
})
}
I have created the below code for a subscribe form and for the most part it is working fine apart from, however the following condition does not seem to be working:
if (subFieldUpdated === true && subValidEmail === true) {
$("#modEmailSub, #modFNameSub, #modLNameSub").val("");
}
What is happening is that when the subValidEmail is entered correctly it clears all of the other entered data which leads me to believe that the subFieldUpdated === true condition is not being picked up correctly?
What I am looking for is that the form will only clear the values once all fields have been entered & a valid email is present.
Any suggestions/advice would be great as I have tried a few things now but with no luck.
$("#modSubCard").submit(function() {
var modSubField = ["#modEmailSub", "#modFNameSub", "#modLNameSub"];
$("#modEmailSub, #modFNameSub, #modLNameSub").removeClass("border-red");
contactValid(modSubField);
function contactValid(field) {
var subFieldUpdated = true;
var subValidEmail = true;
for (var i = 0; i < field.length; i++) {
if ($(field[i]).val() == "") {
$(field[i]).addClass("border-red");
subFieldUpdated[i] = false;
}
if (!validateEmail($("#modEmailSub").val())) {
$("#modEmailSub").addClass("border-red");
subValidEmail = false;
}
if (subFieldUpdated === true && subValidEmail === true) {
$("#modEmailSub, #modFNameSub, #modLNameSub").val("");
}
}
}
});
Use Below Code. It will works for you.
var modSubField = ["#modEmailSub", "#modFNameSub", "#modLNameSub"];
$("#modEmailSub, #modFNameSub, #modLNameSub").removeClass("border-red");
contactValid(modSubField);
function contactValid(field) {
var subFieldUpdated = 0;
var subValidEmail = true;
for (var i = 0; i < field.length; i++) {
if ($(field[i]).val() == "") {
$(field[i]).addClass("border-red");
subFieldUpdated = subFieldUpdated + 1;
}
if (!validateEmail($("#modEmailSub").val())) {
$("#modEmailSub").addClass("border-red");
subValidEmail = false;
}
if (subFieldUpdated === 0 && subValidEmail === true) {
$("#modEmailSub, #modFNameSub, #modLNameSub").val("");
}
}
}
});
In php this is a nice way of asking is a value is one of a few options
if( in_array($needle, [1,325,'something else']) ){
//do your thing
}
But in the world of javascript is there an equiv. that doesn't require writing a bespoke function such as:
function inArray(needle, haystack) {
var length = haystack.length;
for(var i = 0; i < length; i++) {
if(typeof haystack[i] == 'object') {
if(arrayCompare(haystack[i], needle)) return true;
} else {
if(haystack[i] == needle) return true;
}
}
return false;
}
function arrayCompare(a1, a2) {
if (a1.length != a2.length) return false;
var length = a2.length;
for (var i = 0; i < length; i++) {
if (a1[i] !== a2[i]) return false;
}
return true;
}
Use case of the above js bespoke function
if( inArray( somvar, [1,2,'something else']) ){
do the javascript thing
}
FROM THE COMMENTS
this is the most accurate answer: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes
var needle = 325;
if( [1,325,'something else'].indexOf(needle) !== -1 ){
//do your thing
};
You can use Array.prototype.find():
var data = ['Lorem', 'Ipsum', 'Sit']
var foundSit = data.find(function(item){
return item == 'Sit';
});
I cannot get the loop to work in my simple js login script. When i try to login with any login other than the last one in the array (user3 and pass3) it returns false.
What am I doing wrong?
I have tried both == and ===.
var userLogins = [{user:"user1", password:"pass1"},{user:"user2", password:"pass2"},{user:"user3", password:"pass3"}]
var success = null;
function logon(user, pass) {
userok = false;
for (i = 0; i < userLogins.length; i++)
{
if(pass == userLogins[i].password && user == userLogins[i].user )
{
success = true;
}
else
{
success = false;
}
}
secret(success);
}
function getData() {
var user = document.getElementById("userid").value;
var password = document.getElementById("password").value;
logon(user, password);
}
function secret(auth){
if(auth)
{
show('success');
hide('login');
}
else
{
show('error');
hide('login');
}
}
function show(show) {
document.getElementById(show).className = "show";
}
function hide(hide) {
document.getElementById(hide).className = "hide";
}
for (i = 0; i < userLogins.length; i++)
{
if(pass == userLogins[i].password && user == userLogins[i].user )
{
success = true;
}
else
{
success = false;
}
}
You need a break in there, otherwise your true value for success simply gets overwritten with false on the next iteration... except for the last possible credentials, for which there is no "next" iteration.
Once you've done that, you don't actually need the else branch at all:
var success = false;
for (i = 0; i < userLogins.length; i++) {
if (pass == userLogins[i].password && user == userLogins[i].user) {
success = true;
break;
}
}
Use break when you found it. Otherwise the next loop will set success to false.
for (var i = 0; i < userLogins.length; i++)
{
if(pass == userLogins[i].password && user == userLogins[i].user )
{
success = true;
break;
}
else
{
success = false;
}
}
secret(success);