Loop until… with Ramda

2019-02-10 23:54发布

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.

2条回答
狗以群分
2楼-- · 2019-02-11 00:27

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>

查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-02-11 00:43

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 values

Someone else more familiar with Ramda can comment if a similar function already exists in the library

const unfold = (f, init) =>
  f ( (x, next) => [ x, ...unfold (f, next) ]
    , () => []
    , init
    )

const nextLetter = c =>
  String.fromCharCode (c.charCodeAt (0) + 1)

const alphabet =
  unfold
    ( (next, done, c) =>
        c > 'z'
          ? done ()
          : next (c, nextLetter (c))
    , 'a'
    )

console.log (alphabet)
// [ a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z ]

unfold is pretty powerful

const fib = (n = 0) =>
  unfold
    ( (next, done, [ n, a, b ]) =>
        n < 0
          ? done ()
          : next (a, [ n - 1, b, a + b ])
    , [ n, 0, 1 ]
    )

console.log (fib (20))
// [ 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765 ]

We can implement your iterateUntil using unfold

const unfold = (f, init) =>
  f ( (x, acc) => [ x, ...unfold (f, acc) ]
    , () => []
    , init
    )
    
const iterateUntil = (f, init) =>
  unfold
    ( (next, done, [ arr, i ]) =>
        i >= arr.length || f (arr [i], i, arr)
          ? done ()
          : next (arr [i], [ arr, i + 1 ])
    , [ init, 0 ]
    )
  
const data =
  [ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i' ]
  
console.log (iterateUntil ((x, i) => i > 3, data))
// [ 'a', 'b', 'c', 'd' ]

console.log (iterateUntil ((x, i) => x === 'd', data))
// [ 'a', 'b', 'c', 'd' ]

We can make it support asynchrony easily with async and await. Below we use asyncUnfold to perform a recursive db lookup starting with a single node id, 0

  • db.getChildren accepts a node id and returns only the node's immediate children

  • traverse accepts a node id and it recursively fetches all descendant children (in depth-first order)

const asyncUnfold = async (f, init) =>
  f ( async (x, acc) => [ x, ...await asyncUnfold (f, acc) ]
    , async () => []
    , init
    )

// demo async function
const Db =
  { getChildren : (id) =>
      new Promise (r => setTimeout (r, 100, data [id] || []))
  }

const Empty =
  Symbol ()

const traverse = (id) =>
  asyncUnfold
    ( async (next, done, [ id = Empty, ...rest ]) =>
        id === Empty
          ? done ()
          : next (id, [ ...await Db.getChildren (id), ...rest ])
    , [ id ]
    )
    
const data =
  { 0 : [ 1, 2, 3 ]
  , 1 : [ 11, 12, 13 ]
  , 2 : [ 21, 22, 23 ]
  , 3 : [ 31, 32, 33 ]
  , 11 : [ 111, 112, 113 ]
  , 33 : [ 333 ]
  , 333 : [ 3333 ]
  }

traverse (0) .then (console.log, console.error)
// => Promise
// ~2 seconds later
// [ 0, 1, 11, 111, 112, 113, 12, 13, 2, 21, 22, 23, 3, 31, 32, 33, 333, 3333 ]

Other programs that are a good fit for unfold

  • "starting with a page URL /, crawl all descendant pages"
  • "starting with search "foo" and page 1, collect results from all pages"
  • "starting with user Alice, show me her friends, and all of her friends' friends"
查看更多
登录 后发表回答