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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With