[英]How to apply For-Each Loop on Argument Array in Functions in Java Script
[英]Apply same argument to list of functions, and do an operation between each result
我有一个函数列表,每个函数都有相同的参数,并返回一个数字。 我想对每个函数应用一个参数,并对每个连续的结果执行一个操作(在这种情况下为减法):
const run = item => buyPrice(item) -
sellPrice(item) -
receivingCost(item);
有没有一种干净,没有意义的方法来创建此功能?
这并非完全没有意义,但我认为它可以解决某些复杂问题:
const run = lift((b, s, r) => b - s - r)(buyPrice, sellPrice, receivingCost)
虽然我确定我们可以创建(b, s, r) => b - s - r
的无点版本,但我真的怀疑我们能否找到一个具有表达力的版本。
您可以在Ramda REPL上看到这一点。
使用Array.prototype.map()
调用列表中的所有函数,然后使用Array.prototype.reduce()
进行所有减法:
function run (item) {
const funcs = [buyPrice, sellPrice, receivingCost];
return funcs.map(f => f(item)).reduce((x, y) => x - y);
}
我不清楚您要问的是什么,但这是您要找的吗? 想法是将函数保留在数组中,然后使用R.reduce()
减去给定项目的每个函数调用的结果。
编辑 -更新了代码,以使用功能组合更严格地Pointfree
标准。
const reduce = R.reduce; const curry = R.curry; const juxt = R.juxt; const isNil = R.isNil; var item = { buyPrice: 5, sellPrice: 8, receivingCost: 1 }; const getBuyPrice = R.prop("buyPrice"); const getSellPrice = R.prop("sellPrice"); const getReceivingCost = R.prop("receivingCost"); const fns = [getBuyPrice, getSellPrice, getReceivingCost]; const getItemPrices = juxt(fns); const subtract = curry((a, b) => isNil(a) ? b : a - b); const subtractArr = reduce(subtract); const subtractArrFromFirstValue = subtractArr(null); const run = R.compose(subtractArrFromFirstValue, getItemPrices); console.log(run(item));
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.24.1/ramda.min.js"></script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.