2

I have the following JavaScript:

const { inverseDirection } = this.props;

if inverseDirection is false, I need the following:

const dashOffset =
  dashArray - (dashArray * this.state.percentProgress) / 100;

if inverseDirection is true, I need the following:

const dashOffset =
  dashArray + (dashArray * this.state.percentProgress) / 100;

What is the right way to elegantly code this without duplication the entire line?

2 Answers 2

2

You can do

const dashOffset = inverseDirection 
? ( dashArray + (dashArray * this.state.percentProgress) / 100) 
: (dashArray - (dashArray * this.state.percentProgress) / 100)

Not really that elegant but anything more complex would be a waste of time and probably not very readable.

Sign up to request clarification or add additional context in comments.

Comments

1

You could try this:

const { inverse } = this.props;

let calc = (x, y) => (x * y) / 100

let offset = arr + (inverse ? -1 : 1)*(calc(arr, this.state.percentProgress))

This way you can extract/reuse the calc function (or move to utils etc) and the inverse operation boils down to a simply inverse ? -1 : 1 which is what you are really after.

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.