I have an array of objects like:
[{id: 1, parentId: 0, title: 'root'},
{id: 2, parentId: 1, title: 'home'},
{id: 3, parentId: 1, title: 'level 1'},
{id: 4, parentId: 2, title: 'level 2'}]
I would like to create functions on this array so I can use calls like:
var node = library.findById(4);
and also to extend the actual objects themselves so I can create functions like:
var parent = node.parent();
var grandparent = parent.parent();
var children = grandparent.children();
So far I am doing it like this:
// server.js
var library = require('./library').init(nodes);
// library.js
'use strict';
var _ = require('lodash'),
Node = require('./node');
function objectifyNodes(lib, nodes) {
var a = [];
nodes.forEach(function (n) {
a.push(new Node(lib, n));
});
return a;
}
function Library(nodes) {
this.nodes = objectifyNodes(this, nodes);
}
Library.prototype.findById = function(id) {
var x = _.find(this.nodes, function(node) {return node.id === id; });
if (x) { return x; }
return null;
};
module.exports = {
init: function(nodes) {
var lib = new Library(nodes);
return lib;
}
};
// node.js
'use strict';
var _ = require('lodash');
function Node(lib, properties) {
_.extend(this, properties);
this.lib = lib;
}
Node.prototype.parent = function() {
return this.lib.findById(this.parentId);
};
Node.prototype.children = function() {
return this.lib.findByParentId(this.id);
};
module.exports = Node;
Given that they could potentially be 1000's of nodes is this a reasonable way to implement this? Is there a better pattern I could use for a solution?
ids as keys. Then you access a certain node simply bylibrary.nodes[id]. Of course, this only makes sense if you don't care about the ordering of the nodes.id:object, provided the IDs are unique. It could even be{id: {node: obj, parent:obj, grandParent: obj, ...}, id{...}};-)