我有以下JavaScript:
const { inverseDirection } = this.props;
如果inverseDirection为false,则需要以下内容:
const dashOffset =
dashArray - (dashArray * this.state.percentProgress) / 100;
如果inverseDirection为true,则需要以下内容:
const dashOffset =
dashArray + (dashArray * this.state.percentProgress) / 100;
在不重复整行的情况下优雅地编写代码的正确方法是什么?
答案 0 :(得分:2)
你可以
const dashOffset = inverseDirection
? ( dashArray + (dashArray * this.state.percentProgress) / 100)
: (dashArray - (dashArray * this.state.percentProgress) / 100)
并不是那么优雅,但是任何更复杂的事情都会浪费时间,而且可能不太可读。
答案 1 :(得分:1)
您可以尝试以下方法:
const { inverse } = this.props;
let calc = (x, y) => (x * y) / 100
let offset = arr + (inverse ? -1 : 1)*(calc(arr, this.state.percentProgress))
这样,您可以提取/重用calc
函数(或移至utils
等),而inverse
操作可以归结为一个简单的inverse ? -1 : 1
真的在追。