gpt4 book ai didi

javascript - Lodash 递归函数超出最大堆栈大小

转载 作者:行者123 更新时间:2023-11-28 03:07:04 25 4
gpt4 key购买 nike

目标

我正在尝试创建一个“deepMapValues”函数。它将需要一个类似的函数...

(v, k) => k == 'hello' ? 'world' : v;
// if the key is 'hello' then return the value 'world' else return the value that already exists there.

还有一个像...这样的对象

{
hello: true,
foo: {
hello: 'bar'
}
}

并返回对象..

{
hello: 'world',
foo: {
hello: 'world'
}
}

像这样使用它... deepMap(mapFunction)(inputObject)

我当前的功能

我使用 lodash 编写了这个小函数...

const mapValuesWithKey = _.mapValues.convert({ 'cap': false });
// this is because I want both the value and key passed into the map function

deepMap = fn => mapValuesWithKey(
_.cond([
[_.isArray, _.map(deepMap(fn))],
[_.isPlainObject, deepMap(fn)],
[_.T, fn],
])
);

当我运行它时,我立即崩溃......

RangeError: Maximum call stack size exceeded

这是可以预料的,因为该函数是递归的,因此如果操作不正确,它将无限递归。

但是,我将其更改为这个(仅用于测试)...

deepMap = fn => mapValuesWithKey(
_.cond([
[_.T, fn],
])
);

并且它起作用了(这也是预期的)。

但是当我把它改成这样时......

deepMap = fn => mapValuesWithKey(
_.cond([
[_.T, fn],
[_.F, deepMap(fn)],
])
);

它再次崩溃并出现同样的错误。尽管上面的代码中永远不会发生递归,但它仍然超出了调用堆栈大小。

使用 Github 上的 lodash 代码,我怀疑它可能会在运行代码之前评估 _.cond 中的所有对,因此我编写了自己的 cond 版本。

const myCond = pairs => {
return (...args) => {
for (const pair of pairs) {
if (pair[0](args)) {
return pair[1](args)
}
}
}
};

但这仍然崩溃了。

我不确定我现在在这里做错了什么,因为它似乎在递归,即使它不可能递归?

我做错了什么?

谢谢

橡皮鸭编辑

我认为这可能是因为该函数正在使用 fn 参数进行评估,然后在使用 fnrecursive 的 cond 对中创建对象code> 一次又一次地执行相同的操作...

正在调查。

进一步问题

如果上述情况成立...我怎样才能停止错误,但仍然通过递归传递fn

最佳答案

好吧,当我写完问题时我意识到了。递归不是在评估传入对象的函数时发生的,而是在首先创建条件对时发生的。

我将代码更新为这个...

deepMap = fn => _.mapValues(
_.cond([
[_.isArray, _.map(o => deepMap(fn)(o))],
[_.isPlainObject, o => deepMap(fn)(o)],
[_.T, fn],
])
);

这已经排序了。现在,直到评估了条件并且需要运行该函数之后,它才会将 fn 传递到 deepMap 中。

关于javascript - Lodash 递归函数超出最大堆栈大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60523115/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com