I see Binary Tree implementations like this:
var insert = function(value, root) {
if (!root) {
// Create a new root.
root = { val: value };
}
else {
var current = root;
while (current) {
if (value < current.val) {
if (!current.left) {
// Insert left child.
current.left = { val: value };
break;
}
else {
current = current.left;
}
}
else if (value > current.val) {
if (!current.right) {
// Insert right child.
current.right = { val: value };
break;
}
else {
current = current.right;
}
}
else {
// This value already exists. Ignore it.
break;
}
}
}
return root;
}
var exists = function(value, root) {
var result = false;
var current = root;
while (current) {
if (value < current.val) {
current = current.left;
}
else if (value > current.val) {
current = current.right;
}
else {
result = true;
break;
}
}
return result;
}
var traversePre = function(head, callback) {
// Preorder traversal.
if (head) {
if (callback) {
callback(head.val);
}
traversePre(head.left, callback);
traversePre(head.right, callback);
}
}
var traversePost = function(head, callback) {
// Postorder traversal.
if (head) {
traversePost(head.left, callback);
traversePost(head.right, callback);
if (callback) {
callback(head.val);
}
}
}
var traverseIn = function(head, callback) {
// Inorder traversal.
if (head) {
traverseIn(head.left, callback);
if (callback) {
callback(head.val);
}
traverseIn(head.right, callback);
}
}
var traverseInIterative = function(head, callback) {
// Inorder traversal (iterative style).
var current = head;
var history = [];
// Move down to the left-most smallest value, saving all nodes on the way.
while (current) {
history.push(current);
current = current.left;
}
current = history.pop();
while (current) {
if (callback) {
callback(current.val);
}
// Move to the right, and then go down to the left-most smallest value again.
current = current.right;
while (current) {
history.push(current);
current = current.left;
}
current = history.pop();
}
}
var root = insert(10);
insert(5, root);
insert(6, root);
insert(3, root);
insert(20, root);
Particularly, traverseInIterative looks pretty good to me. But I'm wondering if there's really a need to have insert and exists, and likewise to have search or delete. I get that (like in these implementations) that they are implemented differently, but wondering if you could implement a generic matching function that solves all of it in one swoop that would be at the same time as ideal as it gets, performance-wise.
One way to design a generic method to do all the operations would be -
genericMethod(value, root, command)
Here command parameter would receive a string specifying insert or delete or search. And based on the command parameter you can tweak the inner implementation to support all of the operations.
Now let's come to the matter of performance and design perspective. I don't think having a method like this would be ideal. Having a generic method like this would cause you more problem than you can think.
Now after reviewing your code - there are a number of things that can be improved which will give you a better experience in my opinion like -
For insertion/deletion - you need to check if the value already exists or not. So just call exists() method rather writing same codes in those method.
This type of generic behavior ensures that you are not writing same codes again and again also SRP(Single Responsibility Principle), so your code is perfectly compartmentalized and more easily readable.
I am trying to build this simple Javascript Binary search tree. I have simply created the addItem method for the tree, but no item seems to get added to the tree. I have divided the addItem method into several other methods to ensure that the tree reference is passed properly without any errors. I think the problem is occurring in the addNode recursive calls.
Below the is the given code:
class Node{
constructor(value){
this.value=value;
this.left=null;
this.right=null;
}
show(){
console.log(this.value);
}
}
class BST{
constructor(){
this.root=null;
}
addNode(node, item){
if(node==null){
node=new Node(item);
}
else if(item<=node.value){
this.addNode(node.left, item);
}
else {
this.addNode(node.right, item);
}
}
addFunc(tree, item){
this.addNode(tree.root, item);
}
addItem(item){
this.addFunc(this, item);
}
}
let bst = new BST();
bst.addItem(5);
bst.addItem(43);
bst.addNode(12);
console.log(bst); // shows BST{root:null}
One of the problem is in function addNode() at if(node==null){node=new Node(item);}
node is passed as a parameter, which means when this.addNode(tree.root, item); is called
node.a = 5 changes value of tree.root.a to 5
node = 5 just changes the value of this node parameter to 5 but not the actual argument that is tree.root value is not assigned to 5.
More info
First, you've not assigned anything as the root of your tree. Your intent was there with this.root. Next, your logic has you recursing a method rather than recursing your tree.
While you call the addNode() method for each value, you always test the root of your tree for > and < values. So this code will only ever overwrite a single .left or .right value. So recursing your function internally doesn't really do what you expect.
The solution is to recurse the tree looking for the correct slot for the value that is passed into the function.
I've re-written your code a bit and taken some liberties with the API. For instance, creating a new BST will require the starting value to be passed into the constructor (this just helps simplify the code a bit). Next, you'll notice no more recursive functions. The recursive calls are replaced with a while loop that finds the appropriate node to add the new node.
This code actually builds the tree where as your attempt only builds a single level.
Edit refactored into search function
class Node {
constructor(value) {
this.value = value;
this.left = {};
this.right = {};
}
show() {
console.log(this.value);
}
}
class BST {
constructor(value = 0) {
this.root = new Node(value);
}
addNode(item) {
Object.assign(this.search(item), new Node(item));
}
findLeftChild(item) {
return this.search(item).left.value;
}
search(item) {
let found = false;
let foundNode = this.root;
while (!found) {
if (foundNode.value === item) {
break;
} else if (foundNode.value > item) {
foundNode = foundNode.left;
found = foundNode.value === undefined;
} else if (foundNode.value < item) {
foundNode = foundNode.right;
found = foundNode.value === undefined;
}
}
return foundNode;
}
addItem(item) {
this.addNode(item);
}
}
let bst = new BST(5);
bst.addItem(43);
bst.addItem(12);
bst.addItem(6);
bst.addItem(66);
bst.addItem(22);
bst.addItem(4);
bst.addItem(3);
bst.addItem(2);
bst.addItem(1);
console.log("Found: 17 ", bst.search(17).value !== undefined);
console.log("find value less than 12: " + bst.findLeftChild(12));
console.log(JSON.stringify(bst, null, 2)); // shows BST{root:null}
I am trying to extend the findKey algorithm (in nodejs) below to support finding all the instances of child objects in the tree matching the keyObj signature. The original algoritm:
Object.prototype.findKey = function(keyObj) {
var p, key, val, tRet;
for (p in keyObj) {
if (keyObj.hasOwnProperty(p)) {
key = p;
val = keyObj[p];
}
}
for (p in this) {
if (p == key) {
if (this[p] == val) {
return this;
}
} else if (this[p] instanceof Object) {
if (this.hasOwnProperty(p)) {
tRet = this[p].findKey(keyObj);
if (tRet) {
return tRet;
}
}
}
}
return false;
}
My first naive attemption att accomplishing a find all:
Object.prototype.findAllWithKey = function(keyObject) {
let objectCopy = Object.assign({}, this);
console.log('findAll on : \n\n');
console.log(this);
let keyFound = false;
let keysFound = [];
do {
console.log("while loop iteration...");
keyFound = objectCopy.findKey(keyObject);
console.log(keyFound);
if (keyFound) {
keysFound.push(keyFound);
console.log('\n\nkey found:');
objectCopy = JSON.parse(JSON.stringify(objectCopy).replace(JSON.stringify(keyFound)+',', ''));
} else {
console.log('\n\n key not found');
keyFound = false;
}
} while (keyFound !== false);
console.log('Broke out of while loop')
};
The usage is as follows:
let targetObject = response.findAllWithKey({
name: 'GetStatusCode'
});
where the response object contains a js tree structure with multiple children and instances of sub-objects with {name: 'GetStatusCode'} in them.
Can someone point me into right direction for finding a better way to implement this, since the JSON stringify/parsing feels uneccesary, (plus it fails at the last object since no , is provided there, this I can fix, but there has to be a better way of accomplishing findAll).
Turns out I can accomplish a find all using tree traversal, since xml,json or whathever actually is composed as a tree structure. For instance the algorithm for preorder traversal can be used (lodash provides some help for tree traversal in their contrib package).
Object.prototype.findAllWithKey = function(keyObject) {
resultSet = [], i = 0;
_.walk.preorder(this, function(value, key, parent) {
if (keyObject[key] === value) {
resultSet.push(parent);
}
});
return resultSet;
};
I've been working with this bug for a few days now, and I think I've pinpointed the problem area, but I'm not sure why it doesn't work. I think it may have to do with a problem with passing an object by reference, but if that's the case I'm not sure how to apply that solution to my situation.
Basically, I'm working on (as a learning experience) my own implementation of dependency injection (although I've been told my structure is actually called AMD, I'll keep using "DI" until I understand more about the difference). So I'll briefly explain my code, then highlight the problematic part.
The syntax:
This is what my code should do, it's just very very simple DI.
I created scope with a string path, using "/scopeName/subScopeName:componentName" to select a scope, so that code users can select the scope while defining the component in a simple way, using a ":" to select a component from the scope.
There are no interfaces since it's so simple to type check in JS. There are no special component types such as factories, values, etc, every component is treated equally.
var JHTML = new Viziion('JHTML');
JHTML.addScope('/generate');
/* ... snip ... */
JHTML.addComponent('/generate:process', function(nodes) {
/* ... snip - the code inside isn't important here - snip ..*/
}).inject(['/generate:jsonInput']);
The inject function just takes an array of component paths in the order the component's arguments are expected.
Hooks are components stored in the hooks property, and then there's a function returnUserHandle which will return an object consisting of just the hooks, so all of the functions are hidden in closures, and you can feed the code user just the usable methods.
JHTML.addHook('generate', function(jsonInput, process) {
var html = process(jsonInput);
return html;
}).inject(['/generate:jsonInput', '/generate:process']);
var handle = JHTML.returnUserHandle();
/* HTML Generator Syntax - Client */
console.log(handle.generate());
The problem:
To point inject to the correct object intuitively, there's a focus property on the main object, and I thought I could use that.focus ( which is a reference to this.focus) within my different methods such as addComponent and inject to link new functions to the correct location in my scope model and have them still referenced in focus after being created with addComponent or after being called by the focusComponent method, and then inject could find the dependencies, and "wire" them by doing this:
that.focus = function() {
that.focus.apply(null, dependencies);
};
And I thought that would package the dependencies (an array) as a closure and when the code user calls the function, the correct dependencies get applied and that's the ball game. But nope. The functions dont seem to be passing by reference from that.focus into the scope model. that.focus updates, but the scope model does not.
What's wrong with my reference logic?
The code:
Here's a simplified version of the code. I think I've done my best to explain how it works and where exactly the reference problem I'm trying to solve is located.
/* Dependency Injection Framework - viziion.js */
function Viziion() {
var that = this;
//here's the focus property I mentioned
this.focus = null;
this.scope = {
'/': {
'subScopes': {},
'components': {}
}
};
this.hooks = {};
this.addScope = function(scopeName) {
/* the way this works inst relevant to the problem */
};
this.addComponent = function(componentName, func) {
var scopeArray = // snip
// snip - just code to read the component path
for (var i = 0; i <= scopeArray.length; i++) {
if (scopeArray[i] !== "") {
if (scope.subScopes[scopeArray[i]]) {
scope = scope.subScopes[scopeArray[i]];
} else if (i == scopeArray.length) {
// And here's where I add the component to the scope model
// and reference that component in the focus property
scope.components[scopeName] = func;
that.focus = scope.components[scopeName];
} else {
throw 'Scope path is invalid.';
}
}
}
} else {
throw 'Path does not include a component.';
}
return that;
};
this.returnComponent = function(componentName, callback) {
/* ... snip ... */
};
this.addHook = function(hookName, func) {
/* ... snip ... */
};
this.inject = function(dependencyArray) {
if (dependencyArray) {
var dependencies = [];
for (var i = 0; i < dependencyArray.length; i++) {
that.returnComponent(dependencyArray[i], function(dependency) {
dependencies.push(dependency);
});
}
that.focus = function() {
that.focus.apply(null, dependencies);
};
return that;
}
};
/* ... snip - focusComponent - snip ... */
/* ... snip - returnUserHandle - snip ... */
This should, when applied as shown up above under the "Syntax" header, produce a console log with a string of HTML.
Instead, I get TypeError: undefined is not a function, corresponding to the line var html = process(jsonInput);.
If you want to test the full code, all together, here it is:
/* Dependency Injection Framework - viziion.js */
function Viziion(appName) {
if (typeof appName == 'string') {
var that = this;
this.name = appName;
this.focus = null;
this.scope = {
'/': {
'subScopes': {},
'components': {}
}
};
this.hooks = {};
this.addScope = function(scopeName) {
if (typeof scopeName == 'string') {
var scopeArray = scopeName.split('/');
var scope = that.scope['/'];
for (var i = 0; i < scopeArray.length; i++) {
if (scopeArray[i] !== "") {
if (scope.subScopes[scopeArray[i]]) {
scope = scope.subScopes[scopeArray[i]];
} else {
scope.subScopes[scopeArray[i]] = {
'subScopes': {},
'components': {}
};
}
}
}
} else {
throw 'Scope path must be a string.';
}
return that;
};
this.addComponent = function(componentName, func) {
if (typeof componentName == 'string') {
var scopeArray = componentName.split(':');
if (scopeArray.length == 2) {
var scope = that.scope['/'];
var scopeName = scopeArray[1];
scopeArray = scopeArray[0].split('/');
for (var i = 0; i <= scopeArray.length; i++) {
if (scopeArray[i] !== "") {
if (scope.subScopes[scopeArray[i]]) {
scope = scope.subScopes[scopeArray[i]];
} else if (i == scopeArray.length) {
scope.components[scopeName] = func;
that.focus = scope.components[scopeName];
} else {
throw 'Scope path is invalid.';
}
}
}
} else {
throw 'Path does not include a component.';
}
} else {
throw 'Component path must be a string.';
}
return that;
};
this.returnComponent = function(componentName, callback) {
if (typeof componentName == 'string') {
var scopeArray = componentName.split(':');
if (scopeArray.length == 2) {
var scope = that.scope['/'];
var scopeName = scopeArray[1];
scopeArray = scopeArray[0].split('/');
for (var i = 0; i <= scopeArray.length; i++) {
if (scopeArray[i] !== "") {
if (i == scopeArray.length) {
callback(scope.components[scopeName]);
} else if (scope.subScopes[scopeArray[i]]) {
scope = scope.subScopes[scopeArray[i]];
} else {
throw 'Scope path is invalid.';
}
}
}
} else {
throw 'Path does not include a component.';
}
} else {
throw 'Component path must be a string.';
}
};
this.addHook = function(hookName, func) {
if (typeof hookName == 'string') {
that.hooks[hookName] = func;
that.focus = that.hooks[hookName];
} else {
throw 'Hook name must be a string.';
}
return that;
};
this.inject = function(dependencyArray) {
if (dependencyArray) {
var dependencies = [];
for (var i = 0; i < dependencyArray.length; i++) {
that.returnComponent(dependencyArray[i], function(dependency) {
dependencies.push(dependency);
});
}
console.log(that.focus);
that.focus = function() {
that.focus.apply(null, dependencies);
};
console.log(that.focus);
console.log(that.scope);
return that;
}
};
this.focusComponent = function(componentPath) {
that.focus = that.returnUserHandle(componentPath);
};
this.returnUserHandle = function() {
return that.hooks;
};
} else {
throw 'Viziion name must be a string.';
}
}
/* JSON HTML Generator - A Simple Library Using Viziion */
var JHTML = new Viziion('JHTML');
JHTML.addScope('/generate');
JHTML.addComponent('/generate:jsonInput', [{
tag: '!DOCTYPEHTML'
}, {
tag: 'html',
children: [{
tag: 'head',
children: []
}, {
tag: 'body',
children: []
}]
}]);
JHTML.addComponent('/generate:process', function(nodes) {
var html = [];
var loop = function() {
for (var i = 0; i < nodes.length; i++) {
if (nodes[i].tag) {
html.push('<' + tag + '>');
if (nodes[i].children) {
loop();
}
html.push('</' + tag + '>');
return html;
} else {
throw '[JHTML] Bad syntax: Tag type is not defined on node.';
}
}
};
}).inject(['/generate:jsonInput']);
JHTML.addHook('generate', function(jsonInput, process) {
console.log('Process func arg:');
console.log(process);
var html = process(jsonInput);
return html;
}).inject(['/generate:jsonInput', '/generate:process']);
var handle = JHTML.returnUserHandle();
/* HTML Generator Syntax - Client */
console.log(handle.generate());
Big question, bigger answer. Let's get started.
Heavy OOP, Proper Scope
First and foremost, from your code, it looks like you maybe don't fully grasp the concept of this.
Unless you change the execution context of an object's methods beforehand, said object's methods always have their contextual this bound to the object instance.
That is:
function A () {
var that = this;
this.prop = 1;
this.method = function () {
console.log(that.prop);
};
}
new A().method();
is generally equivalent to:
function A () {
this.prop = 1;
this.method = function () {
console.log(this.prop);
};
}
new A().method();
unless method is adjusted before execution with .bind, .call, or .apply.
Why does this matter? Well, if we use our this context properly we can utilize object prototypes. Prototypes serve as a far more elegant solution to defining every method of an object on a per-instance basis.
Here we create two instances, but only ever one method.
function A () {
this.prop = 1;
}
A.prototype.method = function () {
console.log(this.prop);
};
new A().method();
new A().method();
This is important for clarity, and later on is important when you are binding contexts and arguments to functions (!).
Code Hygiene
You can skip this topic if you like (head down to The Problems(s)), since it might be considered out of place, but keep in mind it does relate to part of the problem with the code.
Your code is hard to read.
Here are some thoughts on that.
Prototypes
Use them. You shouldn't need to worry about users changing execution contexts on you, as that's probably a misuse of your program. Security shouldn't be a concern considering they have the source code.
Not much else to say here.
Exit early
If you're doing sanity checks, try to opt out as early in your code as you can. If you need to throw because of a type mismatch, throw right then and there - not 27 lines later.
// Not great
if (typeof input === 'string') {
...
} else throw 'it away';
// Better
if (typeof input !== 'string') throw 'it away';
...
This goes for loops as well - making appropriate use of the continue keyword. Both of these things improve code clarity, and reduce nesting and code bloat.
Loop caching
When you're looping over a data structure, and you plan to use the current element several times within the block, you should save that element in a variable. Accessing elements and properties isn't necessarily a free-OP.
// Not great
for (var i = 0; i < myArray.length; i++) {
if (myArray[i] > 5) callback(myArray[i]);
internalArray.push(myArray[i]);
}
// Better
var len = myArray.length, element;
for (var i = 0; i < len; i++) {
element = myArray[i];
if (element > 5) callback(element);
internalArray.push(element);
}
When used correctly this improves both clarity and performance.
The Problem(s)
First off, what are we really doing here? The whole problem boils down to an overly complicated application of function binds. That is, simply changing the execution contexts of functions.
I'll also state outright that this program has no bug - it's just flawed.
The major crux of the problem would be these three lines
that.focus = function() {
that.focus.apply(null, dependencies);
};
found in the inject method. They don't make any sense. This would cause an infinite recursion, plain and simple. When you define that function, it doesn't care at all what the focus property of that is right then and there. That matters solely at execution time.
Lucky for us, we never actually get that far, since the process component doesn't get bound correctly.
A huge part of the problem is the focus property. In your program, you're using this as a sort of most recent action. A singular history as to what has just occurred. The problem is, you've tried to hot-swap this value in strange ways.
The focus property (and as you'll see later, other properties) is needed however, because of the reverse application of inject. The way you've structured your component/hook registers into inject model requires state to be held between method invocations.
As an end note for this section, the process component function definition would never have returned anything. Even if your model was correct, your input was flawed. handle.generate() would have returned undefined always.
The Answer(s)
So how can we fix this? Well, the first idea would be to scrap it, honestly. The reverse injection model is ugly, in my opinion. The level of indirection involved with the inject method is very confusing from the surface.
But then we wouldn't learn anything, would we?
So really, how do we fix this? Well, much to the dismay of the functional programmers reading, we need to hold more state.
On its own, our focus property can't provide enough information to properly change the execution contexts of our functions.
On top of our focus, which will simply hold a reference to our most recent component value, we need the field (component/hook name), and the fragment (component object, nothing if hook).
Using these two or three values inside inject, we can take our depedancies array, bind it to our focus, and set the resulting function back into our field.
The great thing about the next part is we can actually drop our closure by making the contextual this of our component/hook the unbound function.
The whole operation looks like this:
var focus = this.focus,
fragment = this.fragment,
field = this.field,
hook = function hook () {
return this.apply(null, arguments);
}, func;
dependencies.unshift(focus);
func = Function.prototype.bind.apply(hook, dependencies);
if (fragment) fragment[field] = func;
else this.hooks[field] = func;
Most of this should be pretty straight forward, but there is one piece that may give people some issues. The important thing to remember is we are essentially creating two functions in sequence here, 'discarding' the first in a sense. (It should be noted that this can be done another way with hook.bind.apply, but it creates even more confusing code. This is about as elegant as you can get.)
dependencies.unshift(focus);
func = Function.prototype.bind.apply(hook, dependencies);
First, we add our focus (our original function) to the front of our list of dependencies. This is important in a moment.
Then we invoke Function.prototype.bind using Function.prototype.apply (remembering that function prototype methods also share the function prototype methods. Pretty much turtles all the way down).
Now we pass our bind context, hook, and our prefixed dependencies to apply.
hook is used as the host for bind, whose contextual this is altered by the first element of the array of arguments passed to apply. The remaining elements are unrolled to shape the subsequent arguments of bind, thus creating the bound arguments of the resulting function.
This isn't a very simple concept, so take your time.
The other thing to note is I've dropped focusComponent completely. Its implementation didn't make sense in context. Your model relies on a last input injection, so you'll need to re-implement focusComponent as a method that simply adjusts the focus, field, and fragment states.
A small sub-fix is the process component function. Not going to go into detail here. You can compare and contrast with your original code, the differences are pretty obvious.
JHTML.addComponent('/generate:process', function (nodes) {
return (function build (struct, nodes) {
var length = nodes.length, node, tag;
for (var i = 0; i < length; i++) {
node = nodes[i];
tag = node.tag;
if (!tag) throw '[JHTML] Bad syntax: Tag type is not defined on node.';
struct.push('<' + tag + '>');
if (node.children) {
build(struct, node.children)
struct.push('</' + tag + '>');
}
}
return struct;
}([], nodes));
}).inject(['/generate:jsonInput']);
The Code
Below is what I would consider a fixed version of your code. It's written in a style that I find useful for both clarity and performance.
/* Dependency Injection Framework - viziion.js */
function Scope () {
this.subScopes = {};
this.components = {};
}
function Viziion (appName) {
if (typeof appName !== 'string') throw 'Viziion name must be a string.';
this.name = appName;
this.working = this.field = this.focus = null
this.scope = { '/': new Scope() };
this.hooks = {};
}
Viziion.prototype.addScope = function (scopeName) {
if (typeof scopeName !== 'string') throw 'Scope path must be a string.';
var scopeArray = scopeName.split('/'),
scope = this.scope['/'],
len = scopeArray.length,
element, sub;
for (var i = 0; i < len; i++) {
element = scopeArray[i];
if (element === '') continue;
sub = scope.subScopes[element]
if (sub) scope = sub;
else scope.subScopes[element] = new Scope();
}
return this;
};
Viziion.prototype.addComponent = function (componentName, func) {
if (typeof componentName !== 'string') throw 'Component path must be a string.';
var scopeArray = componentName.split(':'),
len, element, sub;
if (scopeArray.length != 2) throw 'Path does not include a component.';
var scope = this.scope['/'],
scopeName = scopeArray[1];
scopeArray = scopeArray[0].split('/');
len = scopeArray.length;
for (var i = 0; i <= len; i++) {
element = scopeArray[i];
if (element === '') continue;
sub = scope.subScopes[element];
if (sub) scope = sub;
else if (i === len) {
this.fragment = scope.components;
this.field = scopeName;
this.focus = scope.components[scopeName] = func;
}
else throw 'Scope path is invalid';
};
return this;
};
Viziion.prototype.returnComponent = function (componentName, callback) {
if (typeof componentName !== 'string') throw 'Component path must be a string.';
var scopeArray = componentName.split(':'),
len, element, sub;
if (scopeArray.length != 2) throw 'Path does not include a component.';
var scope = this.scope['/'],
scopeName = scopeArray[1];
scopeArray = scopeArray[0].split('/');
len = scopeArray.length;
for (var i = 0; i <= len; i++) {
element = scopeArray[i];
if (element === '') continue;
sub = scope.subScopes[element]
if (i === len) callback(scope.components[scopeName]);
else if (sub) scope = sub;
else throw 'Scope path is invalid';
}
};
Viziion.prototype.addHook = function (hook, func) {
if (typeof hook !== 'string') throw 'Hook name must be a string.';
this.fragment = null;
this.field = hook;
this.focus = this.hooks[hook] = func;
return this;
};
Viziion.prototype.inject = function (dependancyArray) {
if (!dependancyArray) return;
var dependencies = [],
len = dependancyArray.length,
element;
function push (dep) { dependencies.push(dep); }
for (var i = 0; i < len; i++) {
element = dependancyArray[i];
this.returnComponent(element, push);
}
var focus = this.focus,
fragment = this.fragment,
field = this.field,
hook = function hook () {
return this.apply(null, arguments);
}, func;
dependencies.unshift(focus);
func = Function.prototype.bind.apply(hook, dependencies);
if (fragment) fragment[field] = func;
else this.hooks[field] = func;
return this;
};
Viziion.prototype.returnUserHandle = function () { return this.hooks; };
/* JSON HTML Generator - A Simple Library Using Viziion */
var JHTML = new Viziion('JHTML');
JHTML.addScope('/generate');
JHTML.addComponent('/generate:jsonInput', [{
tag: '!DOCTYPE html'
}, {
tag: 'html',
children: [{
tag: 'head',
children: []
}, {
tag: 'body',
children: []
}]
}]);
JHTML.addComponent('/generate:process', function (nodes) {
return (function build (struct, nodes) {
var length = nodes.length, node, tag;
for (var i = 0; i < length; i++) {
node = nodes[i];
tag = node.tag;
if (!tag) throw '[JHTML] Bad syntax: Tag type is not defined on node.';
struct.push('<' + tag + '>');
if (node.children) {
build(struct, node.children)
struct.push('</' + tag + '>');
}
}
return struct;
}([], nodes));
}).inject(['/generate:jsonInput']);
JHTML.addHook('generate', function (jsonInput, process) {
return process(jsonInput);
}).inject(['/generate:jsonInput', '/generate:process']);
var handle = JHTML.returnUserHandle();
console.log(JHTML);
/* HTML Generator Syntax - Client */
console.log(handle.generate());
Function is question is from postcss-discard-duplicates plugin. Here is code in index.js:
'use strict';
var postcss = require('postcss');
function dedupe (node) {
if (node.nodes) { node.each(dedupe); }
if (node.type === 'comment') { return; }
var nodes = node.parent.nodes.filter(function (n) {
return String(n) === String(node);
});
nodes.forEach(function (n, i) {
if (i !== nodes.length - 1) {
n.removeSelf();
}
});
}
module.exports = postcss.plugin('postcss-discard-duplicates', function () {
return function (css) {
css.each(dedupe);
};
});
Plugin uses PostCSS API which returns CSS node tree. Full API is well documented here.
At the moment I have large CSS file build on top of Twitter Bootstrap with lots of complex selectors. CSS takes ~37 sec. to compile if using this function to find and remove any duplicate rules. Without it, it's ~3 sec.
I'm looking for help optimizing this function for better performance.
UPDATE: I posted answer that copied improvements made by function author. It reduces compile time for more than 50%.
I'm not sure that it's easy to find optimisation directly in this function, seems like it's task for profession optimisations with building helping structures like binary tree and so on. It's not easy question, problem in the algorithm, not in the implementation.
If you just want to optimize code - try to merge filter and forEach. At least, it will help to avoid double iterating.
var last = null;
var nodes = node.parent.nodes.forEach(function(n){
if (String(n) === String(node)) {
if (last) {
last.removeSelf();
}
last = n;
}
});
I reported this issue to repo owner and he made some significant performance improvements. My compile time is now ~13.5 sec. (by adding microoptimizations mentioned in question comment I also managed to shave off aditional second)
This is improved code:
'use strict';
var postcss = require('postcss');
function dedupe (node, index) {
if (node.type === 'comment') { return; }
if (node.nodes) { node.each(dedupe); }
var toString = node.toString();
var nodes = node.parent.nodes;
var result = [node];
var i = index + 1;
var max = nodes.length;
for (; i < max; i++) {
if (nodes[i].toString() === toString) {
result.push(nodes[i]);
}
}
for (var x = 0; x < result.length; x++) {
if (x !== result.length - 1) {
result[x].remove();
}
}
}
module.exports = postcss.plugin('postcss-discard-duplicates', function () {
return function (css) {
css.each(dedupe);
};
});