1

I have pushed some data into an array:

if(target === 'create'){
    if(name === 'form[username]' || name === 'form[name]' || name === 'form[slug]' || name === 'form[plainPassword]'){
        errors.push(name);
    }
} else {
    if(name === 'form[username]' || name === 'form[name]' || name === 'form[slug]' ){
        errors.push(name);
    }
}

It actually works fine. But it seems to me that it is really too much repeating code, but I still cannot find a way to reduce the code, or make a simpler better solution.

5
  • are you talking about errors array or form[] ? Commented Nov 26, 2018 at 12:00
  • about errors array Commented Nov 26, 2018 at 12:01
  • looking at this tiny piece of code that you have shown doesn't need any optimization. Commented Nov 26, 2018 at 12:04
  • @Dhiren Indeed, In fact, it could be shorter but it's just an if/else that cost nothing in programming languages. So there is no need to be optimized Commented Nov 26, 2018 at 12:06
  • @ColinCline correct. Commented Nov 26, 2018 at 12:07

3 Answers 3

2

I would do it in two methods

function CheckErrors(target,name){
   switch(target){
     case 'create':
       SaveError(name,true);
       break;
     default:
       SaveError(name);
       break;
    }
}

function SaveError(name,checkPassword){
     if(name === 'form[username]' || name === 'form[name]' || name === 'form[slug]' ||(checkPassword && name === 'form[plainPassword]')){
        errors.push(name);
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

I am afraid you missed something
just trying to figure out what i missed :)
OP dont want to push 'form[plainPassword]' in else statement
indeed i see it. If i had to re-write it would still look ugly
2

You could use arrays to simplify your if statement:

if((target === 'create' && name === 'form[plainPassword]') || ['form[username]', 'form[name]', 'form[slug]'].includes(name)){
  errors.push(name);
}

Comments

1

If I rigth understand you, you want to simplify your statements. From my perspective it could be like this:

if(name === 'form[username]' || name === 'form[name]' || name === 'form[slug]' 
                             || (name === 'form[plainPassword]' && target === 'create')){
    errors.push(name);
}

Since:

name === 'form[username]' || name === 'form[name]' || name === 'form[slug]'

is repeated two times, it doesn't matter if target === 'create' is true or false for this statements.

In fact just add (name === 'form[plainPassword]' && target === 'create') to if statement and that's all

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.