One algorithm for binary tree search, traversal, insertion, and deletion - javascript

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.

Related

Javascript Binary Search Tree methods not working

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}

Understanding function to find mode

Hope this is an ok question to ask here...
So I got a little help creating a function to find mode (the number which appears the most time in an array). But now I need a little help understanding it...
(I'm totally new in programming)
Data is holding the "information", contains multiple arrays in another file.
let mode = function(data) {
data.sort(function(a, b) {
return a - b;
});
let mode = {},
highestOccurrence = 0,
modes = [];
data.forEach(function(element) {
if (mode[element] === undefined) {
mode[element] = 1;
} else {
mode[element]++;
}
if (mode[element] > highestOccurrence) {
modes = [element];
highestOccurrence = mode[element];
} else if (mode[element] === highestOccurrence) {
modes.push(element);
highestOccurrence = mode[element];
}
});
return modes;
};
So at first I'm just sorting the function so the numbers will appear in corret order. But could someone be so kind to help me understand the rest of the function?
I've added some comments that I could infer only be the code you provided. You could provide some more context to your question like what is the kind of data you have and what are you trying to achieve and maybe provide examples that could be useful.
let mode = function(data) {
data.sort(function(a, b) {
return a - b;
});
let mode = {},
highestOccurrence = 0,
modes = [];
// This loops through data array (It should be data here and not data1)
data.forEach(function(element) {
// Here you check if the mode object already have that element key,
// setting the first occurence or incrementing it
if (mode[element] === undefined) {
mode[element] = 1;
} else {
mode[element]++;
}
// After that it checks if that mode has the higher occurence
if (mode[element] > highestOccurrence) {
// If it has the higher occurence it sets the modes to an array with
// that element and the highestOccurrence value to that value
modes = [element];
highestOccurrence = mode[element];
} else if (mode[element] === highestOccurrence) {
// If it has the same number of occurences it just adds that mode to
// the modes to be returned
modes.push(element);
highestOccurrence = mode[element];
}
});
return modes;
};
Hope this helps you

My object isn't updating by reference, what's wrong with the logic?

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());

Implementing eachChild for a specefic case

I have a few places in my code that are very similar to this snippet:
tag_iter = hold_tags_el.firstChild;
do {
if (tag_iter === null) {
hold_tags_el.appendChild(paragraph_el);
break;
}
if (par_el.innerHTML < tag_iter.innerHTML) {
hold_tags_el.insertBefore(paragraph_el, tag_iter);
break;
}
if (tag_iter === hold_tags_el.lastChild) {
NS.insertAfter(tag_iter, paragraph_el);
break;
}
tag_iter = tag_iter.nextSibling;
} while (tag_iter !== null);
This can be abstracted to:
tag_iter = ref_el.firstChild;
do {
// loop logic
tag_iter = tag_iter.nextSibling;
} while (tag_iter !== null);
In a function form this would look like:
The Call:
eachChild(par_el, function (tag_iter, par_el) {
// loop logic
});
The Definition:
NS.eachChild = function (par_el, func, context) {
var iter_el = par_el.firstChild,
result;
do {
result = func.call(context, iter_el, par_el);
if (result) {
break;
}
iter_el = iter_el.nextSibling;
} while (iter_el !== null);
}
Is there a library that implements this pattern / idiom?
What improvements can be made to eachChild?
Are there any errors in eachChild?
Applying the idiom we have:
Snippet A
NS.eachChild(el, function(tag_iter, par_el){
// first
if (tag_iter === null) {
par_el.appendChild(paragraph_el);
return true;
}
// middle
if (par_el.innerHTML < tag_iter.innerHTML) {
par_el.insertBefore(paragraph_el, tag_iter);
return true;
}
// last
if (tag_iter === hold_tags_el.lastChild) {
par_el.appendChild(paragraph_el);
return true;
}
});
What improvements can be made?
Many. Your snippet with its do-while loop and the many breaks is overly complicated and hard to understand. It can be simplified to
var tag_iter = hold_tags_el.firstChild,
search = par_el.innerHTML;
while (tag_iter !== null && search >= tag_iter.innerHTML)
tag_iter = tag_iter.nextSibling;
hold_tags_el.insertBefore(paragraph_el, tag_iter);
Notice that insertBefore with null as second argument, insertAfter(lastChild) and appendChild do exactly the same thing.
With that simplification, you don't need that eachChild function any more. But maybe a little different one:
NS.findChild = function(parent, condition) {
var child = parent.firstChild;
for (var i=0; child!==null && condition(child, i); i++)
child = child.nextSibling;
return child;
};
// then simply:
var el = NS.findChild(hold_tags_el, function(tag_iter) {
return tag_iter.innerHTML < par_el.innerHTML;
});
hold_tags_el.insertBefore(paragraph_el, el);
Is there a library that implements this pattern / idiom?
I don't know any. But there are many libs with generic iterator methods (some of them with break functionality) that can easily be applied on childNodes collections.
Are there any errors in eachChild?
It calls the callback even when there is no firstChild (with null as argument). That's at least unconventional, if not wrong - not what you would expect from an iteration. If you think to need it, this should better be made a separate case (a separate callback); otherwise it requires an extra condition in the callback. However in the given usecase you do not need it, as that is a search - see the findChild function above - where eachChild is inappropriate.
What improvements can be made to eachChild?
Additionally to parEl maybe a counter argument might be nice - check the signature of the standard forEach Array method.

Javascript - Remove references to my object from external arrays

I have a problem with dereferencing a Javascript object and setting it to NULL.
Here, I have a Folder implementation that supports recursive subdirectory removal. Please see my comments to understand my dilemma.
function Folder(name, DOM_rows) {
this.name = name;
this.files = [].concat(DOM_rows);
this.subdirs = [];
}
Folder.prototype.AddDir(name, DOM_rows) {
this.subdirs.push(new Folder(name, DOM_rows));
}
Folder.prototype.RemoveDir(folder) {
var stack = [folder];
while(stack.length > 0) {
var cur = stack.pop();
// do a post-order depth-first traversal, so dig to the deepest subdir:
if(cur.subdirs.length > 0) {
while(cur.subdirs.length > 0) { stack.push(cur.subdirs.pop()); }
} else {
// arrived at a leaf-level:
cur.files = null;
// now how do I delete cur from it's parent's subdirs array?
// the only way I know how is to keep a "cur.parentDir" reference,
// then find parent.subdirs[ index of cur ] and slice it out.
// How can I do the JS-equivalent of *cur = NULL?
}
}
}
Note that you don't have as big a problem as you suspect, since all subdirectories but folder in your RemoveDir will be deleted from their parent's subdir by the stack.push(cur.subdirs.pop()); line
To find a subdirectory in a parent, you could make use an object-as-dictionary rather than an array for subdirs:
function Folder(name, DOM_rows, parent) {
this.name = name;
this.parent = parent;
this.files = [].concat(DOM_rows);
this.subdirs = {};
this.subdirCount = 0;
}
Folder.prototype.AddDir = function (name, DOM_rows) {
if (this.subdirs[name]) {
return null;
}
++this.subdirCount;
return this.subdirs[name] = new Folder(name, DOM_rows, this);
}
Given a folder, you can remove the folder from the parent with:
delete folder.parent.subdirs[folder.name];
Here's a preorder version:
Folder.prototype.RemoveDir = function (folder) {
if (this.subdirs[folder.name] === folder) {
var stack = [folder];
while(stack.length > 0) {
var cur = stack.pop();
// pre-order
delete cur.files;
// if there's other processing to be done, now's the time to do it
for (subdir in cur.subdirs) {
stack.push(cur.subdirs[subdir]);
delete cur.subdirs[subdir];
}
// it's unnecessary to set subdir count, since 'cur' has been deleted
//cur.subdirCount = 0;
}
delete this.subdirs[folder.name];
--this.subdirCount;
}
}
And the recursive post-order version:
Folder.prototype.RemoveChildren = function () {
for (subdir in this.subdirs) {
this.RemoveDir(this.subdirs[subdir]);
}
}
Folder.prototype.RemoveDir = function (folder) {
if (this.subdirs[folder.name] === folder) {
folder.RemoveChildren();
folder.files = [];
delete this.subdirs[folder.name];
--this.subdirCount;
}
}
And the iterative post-order version:
Array.prototype.top = function () { return this[this.length-1]; }
Folder.prototype.RemoveDir = function (folder) {
if (this.subdirs[folder.name] === folder) {
var stack = [folder];
while(stack.length > 0) {
var cur = stack.top();
if (cur.subdirCount > 0) {
for (subdir in cur.subdirs) {
stack.push(cur.subdirs[subdir]);
delete cur.subdirs[subdir];
}
cur.subdirCount = 0;
} else {
stack.pop();
delete cur.files;
// other post-order processing
}
}
delete this.subdirs[folder.name];
}
}
Though, unless you need to take additional steps when processing deleted files & folders, a simple:
Folder.prototype.RemoveDir = function (folder) {
if (this.subdirs[folder.name] === folder) {
delete this.subdirs[folder.name];
}
}
should suffice.
Everything is javascript is passed by value, so "*cur=NULL" is not possible. You basically have the following options here
use parentID as you suggested
if your Folder hierarchy has a well-known root, browse from that root to find the parent object
use something like DOM removeChild (which is called on parent), instead of removeNode (which is called on the node itself).
I was trying to do the same thing today.
I've worked around it by storing the object's index as a property of the object itself.
When you add it:
myObj.ID = myArr.push(myObj);
So to remove it you
myArr[myObj.ID] = null;
I guess you solved it by now, but you could do almost the same; and it's simpler than using objects.

Categories

Resources