Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
282 views
in Technique[技术] by (71.8m points)

javascript - Loop until... with 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)
}

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...