可以使用“transform”来实现带有中断的简化功能版本,例如在underscore中。
我尝试使用配置标志来停止它,以便实现简化的实现不必更改您当前正在使用的数据结构。
const transform = (arr, reduce, init, config = {}) => {
const result = arr.reduce((acc, item, i, arr) => {
if (acc.found) return acc
acc.value = reduce(config, acc.value, item, i, arr)
if (config.stop) {
acc.found = true
}
return acc
}, { value: init, found: false })
return result.value
}
module.exports = transform
用法1,简单的一个
const a = [0, 1, 1, 3, 1]
console.log(transform(a, (config, acc, v) => {
if (v === 3) { config.stop = true }
if (v === 1) return ++acc
return acc
}, 0))
用法2,将配置作为内部变量使用
const pixes = Array(size).fill(0)
const pixProcessed = pixes.map((_, pixId) => {
return transform(pics, (config, _, pic) => {
if (pic[pixId] !== '2') config.stop = true
return pic[pixId]
}, '0')
})
用法3,将配置作为外部变量捕获
const thrusts2 = permute([9, 8, 7, 6, 5]).map(signals => {
const datas = new Array(5).fill(_data())
const ps = new Array(5).fill(0)
let thrust = 0, config
do {
config = {}
thrust = transform(signals, (_config, acc, signal, i) => {
const res = intcode(
datas[i], signal,
{ once: true, i: ps[i], prev: acc }
)
if (res) {
[ps[i], acc] = res
} else {
_config.stop = true
}
return acc
}, thrust, config)
} while (!config.stop)
return thrust
}, 0)
current
是什么?我看不出它们如何执行相同的操作。无论如何,还有一些可能会提前跳出循环的方法,如some
、every
和find
。 - elclanrssome
和every
返回布尔值,而find
返回单个记录,我想要的是运行操作以生成备忘录。current
是当前值。参考 - Julio Marinscurrent
是什么? - elclanrsreduce
中提前退出,你需要使用内置函数来提前退出或者创建自己的帮助函数,或者使用lodash或其他库。请问您能否提供一个完整的示例说明您想要做什么? - elclanrs