如何干掉这些 JS 数学计算
How to DRY These JS Math Computations
我下面有这些重复的数学计算,我想弄清楚如何让它们变干。
const d = store.state.logbook.summary,
AIR = ([d.AIR/d.TOT]*100).toFixed(2),
PIC = ([d.PIC/d.TOT]*100).toFixed(2),
PMC = ([d.PMC/d.TOT]*100).toFixed(2),
VO = ([d.VO/d.TOT]*100).toFixed(2),
TRNG = ([d.TRNG/d.TOT]*100).toFixed(2);
this.chartData = [
100, +AIR, +PIC, +PMC, +VO, +TRNG
]
console.log(this.chartData)
// Returns: [100, 97.44, 84.65, 84.65, 2.56, 12.79]!
您可以获取一个键数组,映射计算值,取消移位 100
并分配给想要的目标。
const
d = store.state.logbook.summary,
data = ['AIR', 'PIC', 'PMC', 'VO', 'TRNG'].map(k => +(d[k] * 100 / d.TOT).toFixed(2));
data.unshift(100);
this.chartData = data;
console.log(this.chartData);
将每个部分拆分成更小的单元只是问题的另一种观点,例如
- 获取对象的值
- 通过获取函数的绑定第一个参数并映射值来获取百分比值
- 将值格式化为最多两位数。
const
getPercent = (whole, part) => part * 100 / whole,
getNumFixed2 = value => +value.toFixed(2),
d = { AIR: 28, PIC: 9, PMC: 2, VO: 56, TRNG: 25, TOT: 120 }, // store.state.logbook.summary,
data = ['AIR', 'PIC', 'PMC', 'VO', 'TRNG']
.map(k => d[k])
.map(getPercent.bind(null, d.TOT))
.map(getNumFixed2);
data.unshift(100);
console.log(data);
我下面有这些重复的数学计算,我想弄清楚如何让它们变干。
const d = store.state.logbook.summary,
AIR = ([d.AIR/d.TOT]*100).toFixed(2),
PIC = ([d.PIC/d.TOT]*100).toFixed(2),
PMC = ([d.PMC/d.TOT]*100).toFixed(2),
VO = ([d.VO/d.TOT]*100).toFixed(2),
TRNG = ([d.TRNG/d.TOT]*100).toFixed(2);
this.chartData = [
100, +AIR, +PIC, +PMC, +VO, +TRNG
]
console.log(this.chartData)
// Returns: [100, 97.44, 84.65, 84.65, 2.56, 12.79]!
您可以获取一个键数组,映射计算值,取消移位 100
并分配给想要的目标。
const
d = store.state.logbook.summary,
data = ['AIR', 'PIC', 'PMC', 'VO', 'TRNG'].map(k => +(d[k] * 100 / d.TOT).toFixed(2));
data.unshift(100);
this.chartData = data;
console.log(this.chartData);
将每个部分拆分成更小的单元只是问题的另一种观点,例如
- 获取对象的值
- 通过获取函数的绑定第一个参数并映射值来获取百分比值
- 将值格式化为最多两位数。
const
getPercent = (whole, part) => part * 100 / whole,
getNumFixed2 = value => +value.toFixed(2),
d = { AIR: 28, PIC: 9, PMC: 2, VO: 56, TRNG: 25, TOT: 120 }, // store.state.logbook.summary,
data = ['AIR', 'PIC', 'PMC', 'VO', 'TRNG']
.map(k => d[k])
.map(getPercent.bind(null, d.TOT))
.map(getNumFixed2);
data.unshift(100);
console.log(data);