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:It looks like you're looking for a reverse fold, or
unfold
.Most people are familiar with
reduce
: it takes a collection of values and reduces it to a single value –unfold
is the opposite: it takes a single value and unfolds it to a collection of valuesSomeone else more familiar with Ramda can comment if a similar function already exists in the library
unfold
is pretty powerfulWe can implement your
iterateUntil
usingunfold
We can make it support asynchrony easily with
async
andawait
. Below we useasyncUnfold
to perform a recursive db lookup starting with a single node id,0
db.getChildren
accepts a nodeid
and returns only the node's immediate childrentraverse
accepts a nodeid
and it recursively fetches all descendant children (in depth-first order)Other programs that are a good fit for
unfold
/
, crawl all descendant pages""foo"
and page1
, collect results from all pages"Alice
, show me her friends, and all of her friends' friends"