Simplify code with two variables? - javascript

I am not sure if I am asking this right, but basically i am trying to simplify my code so I don't have to write the same thing 5 times.
I have included two samples below. You can see that the only thing that changes is the event.X and the ".ia-event-x".
// For title
if (event.title) {
$(".ia-event-title").html(event.title);
$(".ia-event-title").addClass('ia-populated');
}
else if (!event.title) {
$(".ia-event-title").removeClass('ia-populated');
}
// For Description
if (event.description) {
$(".ia-event-description").html(event.description);
$(".ia-event-description").addClass('ia-populated');
}
else if (!event.description) {
$(".ia-event-description").removeClass('ia-populated');
}

Pretty straightforward. Note: This is the shortest solution that assumes all data and DOM follow same pattern.
var array = ['title','description']
for(var i = 0 ; i < array.length; i++){
var s = array[i];
var obj = $(".ia-event-" + s);
if (event[s])
obj.html(event[s]).addClass('ia-populated');
else
obj.removeClass('ia-populated');
}

I created a function that I'm passing my parameters too as needed.
function createPopupContent(eventParameter, eventClass) {
if (eventParameter) {
$(eventClass).html(eventParameter);
$(eventClass).addClass('ia-populated');
}
else if (!eventParameter) {
$(eventClass).removeClass('ia-populated');
}
}

Related

How to save create global variables (with custom name) in a private function

I'm creating an algebra math tool where I take an equation, take the terms, pair like terms, and then evaluate. (I'm making this as a coding exercise)
For the equation a + b - 2a I've gotten the terms saved in an array; ["+a", "+b", "-2a"]. Now what I want is to change this into this:
var lTERMa = ["+a", "-2a"];
var lTERMb = ["+b"];
So far my "fix" is to store the variables in a div element that has white text so you can't see it. It's rather crude, and it doesn't work. Here is the full Javascript code that I've made designed to store them in the div:
function appendinformation(info) {
document.getElementById("hiddenData").innerHTML += info;
}
function runData(bool, int) {
if (bool) {
eval(document.getElementById("hiddenData").innerHTML)
console.log()
}
eval(document.getElementById("hiddenData").innerHTML)
}
var termsViewed = 0;
var lTermsFound = 0;
var seenTerms = []
function processTERMpos(val) {
if (seenTerms.includes(val.replaceAll("+", ""))) {
termsViewed++;
appendinformation(`var lLTERM${val.replaceAll("+", "")} = [${val}]`);
runData()
}
if (!seenTerms.includes(val.replaceAll("+", ""))) {
appendinformation(`lTERM${val.replaceAll("+", "")}.push(${val})`)
runData()
seenTerms.push(val.replaceAll("+", ""))
lTermsFound++;
termsViewed++;
}
}
function processTERMneg(val) {
if (seenTerms.includes(val.replaceAll("-", ""))) {
termsViewed++;
appendinformaion(`var lLTERM${val.replaceAll("-", "")} = [${val}]`);
runData()
}
if (!seenTerms.includes(val.replaceAll("-", ""))) {
appendinformation(`lTERM${val.replaceAll("-", "")}.push(${val})`)
runData()
seenTerms.push(val.replaceAll("-", ""))
lTermsFound++;
termsViewed++;
}
}
for (var i = 0; i < term.length; i++) {
var subject = term[i]
getHiddenData();
eval(hdata);
if (subject.includes("+")) {processTERMpos(subject)}
if (subject.includes("-")) {processTERMpos(subject)}
}
Don't bully me for my bad disorganised coding. I've deleted and reinstated various code, and I'm sure there is code in there than no longer has a use.
If someone could either fix my code, or be able to suggest another way for me to attempt rewriting the code. I've been deleting and rewriting this code for 2 hours and I can't think of any way I can fix it.

Comparing JSON string element with JavaScript string

I have came across an odd problem with getting JSON data like the following.
[
{
"type":"ripe",
"red":137,
"green":68,
"blue":40,
"strftime(\"%H:%M:%S\", time)":"18:46:37"
},
]
I was not able to compare this data by type using JavaScript, they both successfully went through my if statement for some odd reason. The total count for both variables is equal to 2.
let counterLoop = function() {
for (let i = 0; i < data.length; i++) {
let fruitType = JSON.stringify(data[i].type);
sortFruit(fruitType.toLowerCase());
}
}
let sortFruit = function(fruitType) {
if (fruitType.localeCompare('ripe') === 0){} {
totalRipeFruit++;
$("#totalRipeFruit").text(totalRipeFruit);
}
if (fruitType.localeCompare('unripe') === 0){} {
totalUnripeFruit++;
$("#totalUnripeFruit").text(totalUnripeFruit);
}
}
Any idea why this could be the case?
Thank you very much!
You have two problems here; First of all there is no need for the JSON.stringifyon the type, just leave it out as it will return the string containing useless quotes.
Secondly, your if statements are messed up: You have a second pair of brackets behind each one, so simply change
if (fruitType.localeCompare('ripe') === 0){} {
totalRipeFruit++;
$("#totalRipeFruit").text(totalRipeFruit);
}
if (fruitType.localeCompare('raw') === 0){} {
totalRawFruit++;
$("#totalRawFruit").text(totalRawFruit);
}
To:
if (fruitType.localeCompare('ripe') === 0) {
totalRipeFruit++;
}
if (fruitType.localeCompare('raw') === 0) {
totalRawFruit++;
}

FreeCodeCamp: checking for palindromes

This is my first question, so I apologize if this isn't formatted correctly or placed in the proper area.
I just completed the FreeCodeCamp checking for palindromes challenge. I can't help but think my solution was very inelegant.
function palindrome(str) {
var cleanString = str.replace(/[^A-Za-z0-9]/g, '');
var lowerCleanString = cleanString.toLowerCase();
var lowerArr = lowerCleanString.split('');
var reverseArr = lowerArr.reverse();
var joinedArr = reverseArr.join('');
if (joinedArr === lowerCleanString) {
return true;
}
// Good luck!
else {
return false;
}
}
I know it worked, but is it possible to do some of these steps together or in a cleaner way?
Simple function to check for palindromes
function checkPalindrome(palindrome) {
return palindrome == palindrome.split('').reverse().join('');
}
function palindrome(str) {
var newstr = str.replace(/[\W_]/g,'').toLowerCase();
if(newstr === newstr.split('').reverse().join('')){
return true;
}
return false;
}
palindrome("five|\_/|four");
You can use many methods in one row like I've used them .It's more simple :)
Good luck
Wow, I really like the answers comparing the string to a string.split('').reverse().join('') version of itself. I didn't think about that. Forgot about the .reverse() function. I ended up processing the string and splitting it out into an array and then using a double counter for the loop to compare the first and last items in the array. Was kinda fun to learn how to do that, but I like the .reverse() function use better.
In case someone is curious about the for loop I used ...
for(let i = 0, j = arr.length-1; i < j; i++, j--) {
if (arr[i] !== arr[j]) {
return false;
}
}

Multiple OR operators with elem.value.match

I've been writing a javascript function which returns true if the value matches one of about 4 values (just 3 in the example below). The problem is, when I have just two values the function works correctly, but adding a third breaks the code.
I'm pretty new to javascript and I'm guessing there's a much better way of doing this? I've tried searching but found nothing as of yet.
Any help is much appreciated.
function isValid(elem, helperMsg){
var sn6 = /[sS][nN]6/;
var sn5 = /[sS][nN]5/;
var sn38 = /[sS][nN]38/;
if(elem.value.match(sn6 || sn5 || sn38)){
//do stuff
return true;
}else{
return false;
}
}
Edit:
Here's my second attempt with an array:
function isLocal(elem, helperMsg){
var validPostcodes=new Array();
validPostcodes[0]= /[wW][rR]12/;
validPostcodes[1]= /[cC][vV]35/;
validPostcodes[2]= /[sS][nN]99/;
validPostcodes[3]= /[sS][nN]6/;
validPostcodes[4]= /[sS][nN]5/;
validPostcodes[5]= /[sS][nN]38/;
validPostcodes[6]= /[oO][xX]29/;
validPostcodes[7]= /[oO][xX]28/;
var i = 0;
for (i = 0; i < validPostcodes.length; ++i) {
if(elem.value.match(validPostcodes[i])){
// do stuff
return true;
}else{
alert(helperMsg);
elem.focus();
return false;
}
}
}
a || b || c
is an expression that evaluates to a boolean. That means that you're running either match(true) or match(false). You must write it as:
match(a) || match(b) || match(c)
Another option would be to store them in an array and loop over it. That would mean if the number of patterns grew you wouldn't have to change code other than the list of patterns. Another approach, though limited to this situation, might be to change the pattern to one that is equivalent to or-ing the three options together (untested, and I'm a bit rusty on regex):
elem.value.match(/[sSnN][6|5|38]/)
Array based example:
var patterns = [/../, /.../];
for (var i = 0; i < patterns.length; ++i) {
if (elem.value.match(patterns[i])) { return true; }
}
In real code, I would probably format it like this:
function isValid(elem, helperMsg){
var patterns = [/../, /.../],
i = 0;
for (i = 0; i < patterns.length; ++i) {
if (elem.value.match(patterns[i])) {
return true;
}
}
}
That's just a habit though since JavaScript hoists variables to the top of their scope. It's by no means required to declare the variables like that.

Help to implement if-statement with array values

I have a following source code php+js: http://pastebin.org/277948
I want to rewrite it using pure JS, but can’t imagine the way.
Any advices are appreciated.
You can use the every method to test if all elements in the array satisfy the predicate.
if (inp && vals.every(Boolean)) {
// or: vals.every(function(x){return x;})
...
}
But if you have to target browsers that does not support the every method, you can evaluate the condition with a for loop.
if (inp) {
accept = true;
for (var i = vals.length-1; i >= 0; -- i)
if (!vals[i]) {
accept = false;
break;
}
if (accept) {
...
}
}
sorry dont know php but this is the javascript.
if (inp == true) {
for(i =0;i<numFields; i++){
do something with vals[i];
}
}

Categories