I have a concise if/else statement below:
function () {
if (elem.attr('data-src-1') === '' && elem.attr('data-src-2') === '') {
// scenario a
} else if (elem.attr('data-src-1') === '' && elem.attr('data-src-2') !== '') {
// scenario b
} else if (elem.attr('data-src-1') !== '' && elem.attr('data-src-2') === '') {
// scenario c
} else {
// scenario d
}
}
which is returning a complexity of 7 by strict linting rules. I need to reduce its complexity to 6 but can't see how to make it more concise?
More readable one (at least for me)
let data1 = elem.attr('data-src-1') === ''
let data2 = elem.attr('data-src-2') === ''
if (data1)
!data2 ? console.log(" scenario a ") : console.log(" scenario b ")
else
data2 ? console.log(" scenario c ") : console.log(" scenario d ")
This is more of a code review question, but you could combine the if 1='' into if/elses, then do the same for the interiors if/elses.
I think this is less readable, but it is technically less complex.
function() {
if (elem.attr('data-src-1') === '') {
if (elem.attr('data-src-2') === '') {
// scenario a
}
else {
// scenario b
}
} else if (elem.attr('data-src-2') === '') {
// scenario c
}
else {
// scenario d
}
}
Related
I try to get rid of an ugly javscript eval method (Cause we all know it is unsecure).
I have the following problem. I build a dynamic searchstring.
Depends on the TLD a user decided to search for.
Here is my code:
if (tld == 0) {
var searchString = 'value.tld != ""';
}
if (tld == 1) {
var searchString = 'value.tld == "de"';
}
if (tld == 2) {
var searchString = 'value.tld == "com" || value.tld == "net" || value.tld == "org" || value.tld == "info" || value.tld == "biz"';
}
if (tld == 3) {
var searchString = 'value.tld == "io"';
}
Depending on the search parameter 'searchstring', I build this routine with eval:
if (eval(searchString)) {
// Do something special, depends on the tld variable
}
How can i rebuild this without using 'eval'. The premission is, that the first part of the code is beeing untouched.
Thanks in advance
Nick
How about:
let choices = {
1: ['de'],
2: ['com', 'net', 'org', 'info', 'biz'],
3: ['io']
};
function check(tldparam) {
if (tld === 0) {
return value.tld !== "";
} else {
return tld === tldparam && choices[tldparam].includes(value.tld);
}
}
And we test it like:
// Got this value from somewhere
let tld = 2;
let value = {tld: 'net'};
// This is my checking criterion
let tldparam = 2;
if (check(tldparam)) {
// Do something special, depends on the tld variable
}
Does it serve your purpose?
I'm working with Vue in a Laravel app. Everything below works except the last one. I can't seem to find the right search terms to fit this situation. Sorry if it's a duplicate.
Here is my current code:
return [...this.tableData].filter((salesorders) => {
if (this.selectOption == '6') {
return salesorders.order_status.match(this.status);
}
if (this.selectOption == '1') {
return salesorders.number.includes(this.searchInput);
}
if (this.selectOption == '2' && this.choice == 'is') {
var ship_date = moment(String(this.first_date)).format('MM-DD-YYYY');
return salesorders.requested_ship_date.match(ship_date);
}
if (this.selectOption == '2' && this.choice == 'is not') {
var ship_date = moment(String(this.first_date)).format('MM-DD-YYYY');
return !salesorders.requested_ship_date.match(ship_date);
}
if (this.selectOption == '2' && this.choice == 'is between') {
var ship_date1 = moment(String(this.first_date)).format('MM-DD-YYYY');
var ship_date2 = moment(String(this.end_date)).format('MM-DD-YYYY');
return salesorders.requested_ship_date >= ship_date1 && salesorders.requested_ship_date >= ship_date2;
}
});
I just figured it out:
return salesorders.requested_ship_date >= ship_date1 && salesorders.requested_ship_date <= ship_date2;
iam new on React and have a Project where i have to implement a react joyride tour into a finished tool.
currently i have this if condition to check on which page iam, to set the right steps.
if (this.props.location.pathname === '/') {
steps = []
} else if (this.props.location.pathname === '/matches/' || this.props.location.pathname === '/matches') {
if (this.props.firstPartClicked === true) {
steps = matchSiteStepsOne
} else if (this.props.secondPartClicked === true) {
steps = matchSiteStepsTwo
} else {
steps = matchSiteSteps
}
} else if (this.props.location.pathname.startsWith('/matches/') && this.props.location.pathname.endsWith('/edit/') && this.props.location.pathname.match('\\d+')) {
if (this.props.firstPartClicked === true) {
steps = matchEditorStepsOne
} else if (this.props.secondPartClicked === true) {
steps = matchEditorStepsTwo
} else {
steps = matchEditorSteps
}
} else if (this.props.location.pathname.startsWith('/matches/') && this.props.location.pathname.includes('sequence')) {
if (this.props.firstPartClicked === true) {
steps = matchSequenceStepsOne
} else if (this.props.secondPartClicked === true) {
steps = matchSequenceStepsTwo
} else {
steps = matchSequenceSteps
}
} else if (this.props.location.pathname.startsWith('/matches/') && this.props.location.pathname.match('\\d+')) {
steps = matchSteps
}
now my question is if is there a way to make it more generic so i can easily expand more steps on different pages, without so much redundant code?
You can reduce redundant code a little by only looking up pathname once, and storing it in a variable as in
pathname = this.props.location.pathname
This should make your if statements a bit shorter and easier to read. You could also deduplicate some code if e.g. you replaced matchSiteSteps with matchSteps['Site'], and called a function three times with a body like:
if (this.props.firstPartClicked === true) {
steps = matchStepsOne[type]
} else if (this.props.secondPartClicked === true) {
steps = matchStepsTwo[type]
} else {
steps = matchSteps[type]
}
}
I'm writing code in vanilla JavaScript but I don't want to write a thousand different if statements.
I already tried searching up how to reduce if statements in JavaScript, but I didn't find anything helpful.
Here is some example code:
if (a == "text" && b == "othertext") {
console.log("message");
} else if (a == "text2" && b == "othertext2") {
console.log("other message");
} else if (a == "text3" && b == "othertext3") {
console.log("other other message");
} else if (a == "text4" && b == "othertext4") {
console.log("other other other message");
} else if (a == "text5" && b == "othertext5") {
console.log("other other other other message");
} else if (a == "text6" && b == "othertext6") {
// .. and so on.
}
If anyone can help me, it would be appreciated
You can use a data-driven approach by using the strings as keys in an object.
const messages = {
"text|othertext": "message",
"text1|othertext1": "message1",
"text2|othertext2": "message2"
};
function showMessage(a, b) {
let key = `${a}|${b}`;
if (messages.hasOwnProperty(key)) {
console.log(messages[key]);
} else {
console.log("Invalid a and b");
}
}
showMessage("text", "othertext");
You could use ternary operators I suppose.
let msg = '';
msg = a === 'text' && b === 'othertext' : msg;
msg = a === 'text2' && b === 'othertext2' : msg;
// etc.
Ultimately its not gonna get much prettier but that might be a little bit simpler to type.
I have this:
if (THIS.target.hasClass('icon-false-shape')) {
$(this).addClass('white-font');
if (THIS.answer === false) {
console.log('EVERYTHING COMES GREEN');
$(this).addClass('background-green');
} else {
$(this).addClass('background-red');
}
}
if (THIS.target.hasClass('icon-true-shape')) {
$(this).addClass('white-font');
if (THIS.answer === true) {
console.log('EVERYTHING COMES GREEN');
$(this).addClass('background-green');
} else {
$(this).addClass('background-red');
}
}
which I am trying to turn into this:
$(this).addClass('background-' + ((THIS.target.hasClass('icon-false-shape') && THIS.answer === false) ? 'green' : 'red'))
.addClass('white-font');
$(this).addClass('background-' + ((THIS.target.hasClass('icon-true-shape') && THIS.answer === true) ? 'green' : 'red'))
.addClass('white-font');
But my logic is failing.
Any suggestions?
I would use $.toggleClass, that handles condition internally - see:
$(this).addClass('white-font');
$(this).toggleClass('background-green', THIS.answer === true);
$(this).toggleClass('background-red', THIS.answer === true);
Or catching both cases, moving the condition in a separate variable:
var shouldBeGreen = THIS.target.hasClass('icon-false-shape') && THIS.answer === false;
var shouldBeRed = THIS.target.hasClass('icon-true-shape') && THIS.answer === true;
$(this).toggleClass('background-green', shouldBeGreen);
$(this).toggleClass('background-red', shouldBeRed);
First we focus on the condition to be either red or green (in this case I use the criteria to be "red"):
(THIS.target.hasClass('icon-false-shape') && THIS.answer !== false)
or, (THIS.target.hasClass('icon-true-shape') && THIS.answer === false)
if none of the criteria is met, it should be "green".
$(this).addClass('white-font background-' + (((THIS.target.hasClass('icon-false-shape') && THIS.answer !== false) || (THIS.target.hasClass('icon-true-shape') && THIS.answer === false)) ? 'red' : 'green'));
Also note that you can use a space to add multiple classes $(this).addClass("white-font " + ...)" instead of this $(this).addClass(...).addClass("white-font") .