I would prefer to be using ‘new’ on a class to make a node instance, but it does seem cleaner to me. Is it a bad idea though?
Testing some outputs
const linkedList = new LinkedList()
linkedList.insertBefore('A')
linkedList.insertBefore('B')
console.dir(linkedList)
v LinkedList
v head:
data: "B"
v next:
data: "A"
next: null
v tail:
data: "A"
next: null
> __proto__: Object
If we need to use an object prototype method
const has = Object.prototype.hasOwnProperty
console.log(has.call(linkedList.head, 'data')) // true
It was just a thought, and may well be ill advised.
There doesn’t appear to be a way using classes (syntactic sugar, just to get that in) to replicate Object.create(null).
I know that you’re wanting to prefer to use the new operator, but that has been a bad idea. The new keyword was to make Java programmers more comfortable with JavaScript, but didn’t work well because people wouldn’t know of they needed to use new or not, and if they used it when they shouldn’t or didn’t when they should, it broke things in strange and interesting ways.
I’d just like to note that both those articles are from pre-ES2015 when the actual class construct was introduced, which solves the issues of the cumbersome “manual” constructor / prototype definition and related confusion. Factories still allow for more fine-grained control on a lower level (such as enumerability), but most of the time the use of classes is just fine IMHO.
Prefer was probably the wrong word. It was more for consistency. New is used on the linkedlist class, and it seemed a bit off then having a factory function for the node class.
My idea, was to keep the node objects as separate entities without proto links to Object.prototype. For one it made the console.log output easier to decipher without the addition of proto links in the mix. It was just an idea:)
I have looked at numerous tutorials on linked lists, with all of them having different implementations. For instance some use a tail node, some rely on loops to find the last node. Some find by value, some by index. One thing that does seem to be consistent is keeping the node class separate to the linked list class. I’m guessing this is by design? Not as tightly coupled perhaps? I don’t know.
I did change things around a bit, following the course’s implementation, in that the node function now takes two other arguments, previous and next, which gives it a bit more of a reason to be a reusable function.
Anyway if of any interest, this is where I left it yesterday. I opted for using a mock index. It still needs a remove method and could have a length property, but I think I am getting the gist of linked list.
The generator and yield method, which gives you the facility of using a for of loop was taken from here and is something I want to read up on.