1

I'm trying to create a method on a LinkedList constructor that can takes in a function and call that on each node item. This is what I have so far:

this is my constructor:

function LinkedList() {
  this.head = this.tail = null;
}

I have a addToTail method that I tested and works:

LinkedList.prototype.addToTail = function (item) {
  let newNode = new ListNode(item);

  if (this.tail) {
    this.tail.next = newNode;
    newNode.prev = this.tail;
    this.tail = newNode;
  } else {
    this.head = newNode;
    this.tail = this.head;
  }
  return this; 
};

where:

function ListNode(item, prev, next) {
  this.item = item;
  this.next = next || null;
  this.prev = prev || null;
}

Now I'm trying to call a function on each node item:

LinkedList.prototype.forEach = function (iterator) {
  return this.map(iterator (item))

Can anyone explain to me why my forEach returns a []? Also i tried console.log(this) and also got []. What would be the best way to approach this? Thank you!

3
  • Show us how you defined LinkedList.prototype.map. Since you (incorrectly) forward there, it should be obvious why it returns an array. Commented May 19, 2017 at 4:45
  • 'item' in iterator(item) will be undefined. Commented May 19, 2017 at 4:54
  • I was trying to use the Array.prototype.map() method. But I just remembered my linked list isn't an array so I'm now completely lost Commented May 19, 2017 at 5:00

1 Answer 1

2

Maybe, it is not the best solution, however, you can iterate via your linked list and execute the function func on each member:

LinkedList.prototype.forEach = function (func) {
  let cur = this.head;
  while (cur) {
    func(cur); // Call your function
    cur = cur.next;
  }
};

Or, if you want to add a map function to your linked list,

LinkedList.prototype.map = function (func) {
  let res = [];
  let cur = this.head;
  while (cur) {
    res.push(func(cur)); // Call your function and add the result
    cur = cur.next;
  }
  return res;
};

then, you can call:

LinkedList.prototype.forEach = function (func) {
  this.map(function (e) { return e; }).forEach(func);
};
Sign up to request clarification or add additional context in comments.

3 Comments

If you find this Answer useful, please show it to others by an upvote or solved state. Maybe, someone else has a similar question.
I gave it an upvote! :) Sorry I'm a student and still very new to stackoverflow
Thank you. You can upvote answers and you can mark an answer as the answer that fits best to your question. Welcome to StackOverflow!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.