1

I have two functions in my angular project, one is aceitaProposta that does this:

aceitaProposta() {
    this.aceita();
    // some other code
}

and I have recusaProposta:

recusaProposta() {
    this.recusa();
    // some other code
}

Now, the only difference between this.recusa and this.aceita is that the first one increments a property and the second one decrement it. I want to know if there's a way that I can transform these two functions into one function only using something like if to identify if its decrementing or incrementing. This way I would call the same function in both aceitaProposta and recusaProposta. Example:

aceitaProposta() {
   this.incrementDecrement();
    // some other code
}

recusaProposta() {
    this.incrementDecrement();
    // some other code
}
3
  • 3
    Sure, you can pass a boolean to the function to indicate whether the value should be incremented or decremented. Commented Apr 25, 2017 at 16:42
  • 4
    this.add(1), this.add(-1). Commented Apr 25, 2017 at 16:44
  • Why do you need one function to do two different things? It's better to keep them separate instead of adding control flow to something that's supposed to be simple. Commented Apr 25, 2017 at 16:49

3 Answers 3

2

Should be pretty easy.

function incrementDecrement(inc: boolean)
{
    inc ? this.prop++ : this.prop--;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Might as well be this.prop += inc - !inc; For clarity, use an if/else statement.
They've tagged the question with angular, so I think it's good to show a TypeScript answer here too.
1

@KingFelix has it. Just pass a boolean.

incrementDecrement(shouldIncrement: boolean) {
  shouldIncrement ? value++ : value--;
}

aceitaProposta() {
    this.incrementDecrement(true);
}

recusaProposta() {
    this.incrementDecrement(false);
}

1 Comment

oh, that's it. Thank you very much
1

Another way to do this uses ES6 and more 'functional' code. Make the parameter a function instead of a boolean. Then make the change in the function you pass.

update(alteration) {
    x = alteration(x);
}

aceitaProposta() {
    this.update((x) => x - 1);
}

recusalProposta() {
    this.update((x) => x + 1);
}

Without ES6 its a little ugly but you would just add in the anonymous function declarations.

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.