gpt4 book ai didi

javascript - 使用递归函数时如何避免模块之间的循环依赖?

转载 作者:行者123 更新时间:2023-12-05 04:59:41 24 4
gpt4 key购买 nike

以下代码遍历一个对象及其键。它根据每个键所引用的值的类型为每个键做一些事情。它运作良好。一切都很好。

const obj = {
prop1: {
prop2: 1,
prop3: {
prop4: 2
}
},
prop5: "1"
}

function inspectRecursively(node) {
switch (typeof node) {
case "object":
handleObject(node);
break;
case "string":
handleString(node);
break;
case "number":
handleNumber(node);
break;
default:
break;
}
}

function handleObject(node) {
console.log(JSON.stringify(node, null, 2))

for (const [key] of Object.entries(node)) {
inspectRecursively(node[key]);
}
}

function handleString(node) {
console.log(node)
}

function handleNumber(node) {
console.log(node.toString().padStart("0", 3))
}

inspectRecursively(obj)

说我认为文件变得太大了。我把它分成模块

ma​​in.js

import { importRecursively } from "./importRecursively"

const obj = {
prop1: {
prop2: 1,
prop3: {
prop4: 2
}
},
prop5: "1"
}
inspectRecursively(obj)

importRecursively.js

import { handleObject } from "./handleObject.js"
import { handleString} from "./handleString.js"
import { handleNumber} from "./handleNumber.js"

function inspectRecursively(node) {
switch (typeof node) {
case "object":
handleObject(node);
break;
case "string":
handleString(node);
break;
case "number":
handleNumber(node);
break;
default:
break;
}
}

handleObject.js

import { importRecursively } from "./importRecursively"

function handleObject(node) {
console.log(JSON.stringify(node, null, 2))

for (const [key] of Object.entries(node)) {
inspectRecursively(node[key]);
}
}

handleString.js

function handleString(node) {
console.log(node)
}

handleNumber.js

function handleNumber(node) {
console.log(node.toString().padStart("0", 3))
}

现在我以循环依赖告终。

main -> inspectRecursively -> handleObject -> importRecursively

我认为这很糟糕,但我不确定?

遇到这种情况我该怎么办?我是否需要更改某些内容以避免循环依赖?

最佳答案

I think this is bad, but am not sure about it?

不,还不错。 ES6 模块确实可以很好地处理这样的循环依赖。只需确保所有这些模块都是纯模块并且只包含函数声明,而不是构造依赖于导入值的值的顶级代码:声明跨模块“提升”。

Do I change something to avoid the circular dependency?

您可以通过使用显式依赖注入(inject):

// inspectRecursively.js
import { makeHandleObject } from "./handleObject.js"
import { handleString} from "./handleString.js"
import { handleNumber} from "./handleNumber.js"

const handleObject = makeHandleObject(inspectRecursively);

function inspectRecursively(node) {

}
// handleObject.js

export function makeHandleObject(inspectRecursively) {
return function handleObject(node) {

};
}

关于javascript - 使用递归函数时如何避免模块之间的循环依赖?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63414806/

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