I'm trying to understand how to create objects in js using prototypal inheritance i.e using Object.create() instead of the new keyword. I created a node class for the purposes of making a tree data structure using the implementation below:
Object.prototype.extend = function(extension) {
var hasOwnProperty = Object.hasOwnProperty;
var object = Object.create(this);
for(var property in extension) {
if (hasOwnProperty.call(extension, property) ||
typeof object[property] === "undefined")
object[property] = extension[property];
}
return object
}
const node = {
create: function (value, left=null, right=null) {
return this.extend({
value: value,
left: left,
right: right,
})
},
insertLeft: function(value){
this.left = this.create(value);
return this.left;
},
insertRight: function(value) {
this.right = this.create(value);
return this.right;
}
}
The extend function I received from a blog post explaining prototypal inheritance.
I then made a function to validate a BST implemented as such:
validateBST = function (root) {
if (root === null) return true
return (function validate(root, min=-Infinity, max=Infinity) {
if (root === null) return true
if (root.val <= min || root.val >= max) return false
return validate(root.left, min, root.val) && validate(root.right, root.val, max)
})(root)
}
I initialize my tree using the create method in my node object.
let tree = node.create(5, node.create(1), node.create(4, node.create(3), node.create(6)));
Output of tree variable;
{ value: 5,
left: { value: 1, left: null, right: null },
right:
{ value: 4,
left: { value: 3, left: null, right: null },
right: { value: 6, left: null, right: null } } }
So this is an invalid BST but my function returns true, why?
valueproperty your testing forval:(root.val <= minObject.extendis contributing. It seems likenode.createcould simply becreate: function (value, left=null, right=null) { return Object.assign(Object.create(node), { value, left, right }) }Object.assignis a much simpler design.extendfunction or theObject.assignmethod you suggested.