循环直到...与Ramda [英] Loop until... with Ramda
本文介绍了循环直到...与Ramda的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图使用Ramda重构几段代码,我想知道,在Ramda / Functional Programming中解决以下代码可能是一个很好的方法:
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的 直到
可能是你需要的:
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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文