Lazy but finite reduce for recursive data structures and an unbounded number of reducers (see comments)
See original GitHub issueGood day everyone!
Over the past weeks we’ve been working with arbitrarily nested objects and arrays (mixed altogether), up until we’ve spotted the necessity of a recursive reduce function that could be used to transform, but at least to obtain, certain if not every property of this nested structure, which could also be stopped at any given point if a condition is sufficient. Essentially, we’ve been looking at what in haskell would be a fold takeWhile
, but for deep/recursive objects/arrays.
After several iterations, the function valid for these use cases that we haven’t been able to simplify anymore is the following:
// Recursive fold takeWhile (like in haskell)
// fn is the iterator
// obj is the iteratee
// r is the accumulator
const foldWhile = (fn, obj, r = []) => {
let innerFold = o => !(typeof o === 'object') ? o
: Object.keys(o).every(k => fn(r, o[k], k) && innerFold(o[k]))
innerFold(obj)
return r
}
Note: this is implemented with lodash in our code, but since it doesn’t need lodash, I’m using generic es6 to show what it does.
Note2: Besides using functions from the Ramda ecosystem, this would benefit from a trampoline.
The main point of the function is combining the use of every
recursively to stop at any point of the (lazy) evaluation of the nested object/array, with the use of an accumulator, which is handled to the user.
To see use cases and tests, see this gist: https://gist.github.com/sadasant/de106b879c61f21797dffdaa577f7868
We have been looking for opensource alternatives, but we haven’t been successful.
I know that there have been several issues in this repo about lazy evaluation and nested data structures, however there doesn’t seem to be an agreement on how to combine both the nested structures and the stopping of the fold at any given point. I know that Ramda has reduceWhile and until, but they don’t work over nested structures, right?.
Having that said,
I wonder if this is interesting to anybody. We would definitely prefer using opensource instead of maintaining our own code.
Thank you for the time.
Issue Analytics
- State:
- Created 7 years ago
- Reactions:10
- Comments:55 (16 by maintainers)
Why was this issue closed when the PR (#2133) is still open? And why is the PR still open?
i’m interested in seeing a PR for this