0

Say I have a class like so:

class Foo {

 constructor(){
  this.internalList = new Set([1,2,3])
 }

}

is there some method I can implement like so:

class Foo {

 constructor(){
  this.internalList = new Set([1,2,3])
 }

 toArray(){   // add this method

     const ret = [];
     for(const v of this.internalList){
         ret.push(v);
     }
     return ret;
  }

}

so that I can call this:

  const v = Array.from(new Foo());

so is there some interface or method that I can fulfill so that Array.from will work on my class?

3
  • 1
    Make the object iterable. Implement Symbol.iterator: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Sep 6, 2019 at 17:27
  • Note, you could also just have your class inherit from Set and then it would automatically be iterable as the object itself would be an iterable Set with all the methods and capabilities of a Set object. Commented Sep 6, 2019 at 19:13
  • That's true, you could also upvote beautiful questions from thirsty overflowers Commented Sep 7, 2019 at 1:14

1 Answer 1

3

The interface you are looking for is iteration, which Array.from uses. You can simply do

class Foo {
  constructor(){
    this.internalList = new Set([1,2,3])
  }
  [Symbol.iterator]() {
    return this.internalList.values();
  }
}

The values method of the Set creates an iterator that we can use here, but you could also implement a custom iterator.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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