我试图使用Ramda重构几段代码,我想知道,在Ramda / Functional Programming中解决以下代码可能是一个很好的方法:
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)
}
所以基本上我想迭代并在arrayOfSomething上应用相同的管道/操作组合,直到满足其中一个条件。重要的是我将最后一个值(nextValue)作为对forLoop组合的反馈。
答案 0 :(得分:4)
看起来您正在寻找反向折叠或unfold
。
大多数人都熟悉reduce
:它需要一组值,将减少到一个值 - unfold
则相反:它需要一个值, 展开到一组值
如果库中已经存在类似的功能,那么更熟悉Ramda的人可以发表评论
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
非常强大
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 ]
我们可以使用iterateUntil
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' ]
我们可以使用async
和await
轻松支持异步。下面我们使用asyncUnfold
从单个节点id 0
db.getChildren
接受节点id
并仅返回节点的直接子项
traverse
接受一个节点id
,并以递归方式提取所有后代子节点(按深度优先顺序排列)
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 ]
其他适合unfold
/
开始,抓取所有后代网页”"foo"
和页面1
开始,收集所有网页的结果”Alice
开始,向我展示她的朋友,以及她所有朋友的朋友”答案 1 :(得分:3)
我不知道这是否符合您的要求,但Ramda的until
可能就是您所需要的:
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>