本文介绍了循环直到...使用 Ramda的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图使用 Ramda 重构几段代码,我想知道在 Ramda/函数式编程中什么是解决以下代码的好方法:
I was trying to refactor few pieces of code using Ramda and I was wondering, What could be a good approach in Ramda/Functional Programming to solve the following code:
let arrayOfSomething = initArray();
for(let i = 0; SOME_INDEX_CONDITION(i)|| SOME_CONDITION(arrayOfSomething); i++) {
const value = operation(arrayOfSomething);
const nextValue = anotherOperation(value);
arrayOfSomething = clone(nextValue)
}
所以基本上我想迭代并在 arrayOfSomething 上应用相同的管道/操作组合,直到满足其中一个条件.给我最后一个值 (nextValue) 作为对 forLoop 组合的反馈很重要.
So basically I want to iterate and apply the same pipe/composition of operations over arrayOfSomething until one of the conditions is satisfied. Is important that I am given the last value (nextValue) as feedback to the forLoop composition.
推荐答案
我不知道这是否符合您的要求,但是 Ramda 的 until
可能是您所需要的:
I don't know if this does what you want, but Ramda's until
might be what you need:
const operation = ({val, ctr}) => ({val: val % 2 ? (3 * val + 1) : (val / 2), ctr: ctr + 1})
const indexCondition = ({ctr}) => ctr > 100
const valCondition = ({val}) => val === 1
const condition = R.either(indexCondition, valCondition)
const check = R.until(condition, operation)
const collatz = n => check({ctr: 0, val: n})
console.log(collatz(12))
// 12 -> 6 -> 3 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1 //=> {"ctr": 9, "val": 1}
console.log(collatz(5))
// 5 -> 16 -> 8 -> 4 -> 2 -> 1 //=> {"ctr": 5, "val": 1}
console.log(collatz(27))
//27 -> 82 -> 41 -> 124 -> 62 -> .... //=> {"ctr": 101, "val": 160}
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.js"></script>
这篇关于循环直到...使用 Ramda的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!