【发布时间】:2019-09-22 15:39:39
【问题描述】:
有这个代码
const myMagic = (one, two, three, four) => `this is ${one} and ${two} and ${three} and ${four} as usual`
const txt = 'HELLO&ho&hy&hu&hq&HELLO&ho&hy&hu&hq&HELLO&ho&hy&hu&hq&HELLO&ho&hy&hu&hq&hx'
const fragments = txt.split('&')
const pieces = []
for (let i=0; i<fragments.length-1;i +=5) {
pieces.push(fragments[i])
pieces.push(myMagic(fragments[i+1],fragments[i+2],fragments[i+3],fragments[i+4]))
}
pieces.push(fragments[fragments.length-1])
console.log(pieces)
如何将其转换为更具声明性的版本?
代码就是这样,因为拆分采用了一个只解析一次文本的正则表达式,然后使用这些片段,我使用myMagic 函数构建了所需的组件
那么有什么方法可以在不改变逻辑的情况下以更具声明性的方式编写它?
【问题讨论】:
-
定义“更具声明性”...?您需要以五个为一组进行循环。没有一个内置的数组函数可以做到这一点。您可以将其硬塞到其中之一中(也许),但这只会让您变得清晰恕我直言。
-
@T.J.Crowder 幸运的是,我们可以用 Javascript 编写自己的组合子,并采用 FP 中的通用组合子,然后组合/组合它们以允许声明性算法也用于给定任务。
-
@bob - 确实是,FP 或其他...
标签: javascript for-loop functional-programming declarative-programming