Reputation: 184
I am looking for a clean design pattern in Node.js to allow me to put two classes in separate modules when each references the other.
Eg: I have Node
and NodeCollection
objects. Obviously NodeCollection
must know what a Node
is, but Nodes
themselves hold a NodeCollection
object for their children.
Currently I am configuring the Node constructor when I require it.
nodeCollection.js
const Node=require('./node')(NodeCollection)
function NodeCollection(....){
// do stuff with Node objects
}
module.exports = NodeCollection'
node.js
function Node(NodeCollection){
function _Node(...){
this.children = new NodeCollection();
//do stuff
}
return _Node;
}
module.exports = Node;
Is there a better way to design this?
Addendum: There seems to be some misunderstanding: I am not asking for a better design of NodeCollection or Node objects. These were offered as a toy example. Often, in such examples, the two classes cannot be agnostic about each other. I am looking for a way to set up Node.js Modules when faced with such an arrangement. I could solve the problem by putting both classes in the same module but they are large and complex enough that they warrant their own files. Thankyou
Upvotes: 0
Views: 58
Reputation: 3144
I don't think in your case you need to distinguish between Node
and Nodes
. Something basic like this will give you a tree structure.
class Node {
constructor(data) {
this.data = _.omit(data, 'children');
this.children = (data.children || []).map(child => new Node(child));
}
}
const tree = new Node({
name: 'bob',
children: [
{ name: 'bill' },
{ name: 'jim' },
{ name: 'luke' }
]
});
// yields...
{
data: {name: 'bob'},
children: [
{
data: {name: 'bill'}
}
...etc
]
}
Upvotes: 1