JS - returning values from class after instantiated

Viewed 48

I am looking at the code below and want to return the teams array in reverse order when calling the following code. Unfortunately this code cannot be changed.

return Array.from(new TeamsCollection()).join(',')

I know that I can change the constructor to the following:

 constructor(){
    return this.teams.reverse();
 }

As you can see below I am unable to edit the constructor so there must be something else I am missing out on. After reading countless stack overflow answers and searching through online resources I am unable to figure out what to do. Any ideas? See the code below

class TeamsCollection {
    get teams() {
        return [
            'Liverpool',
            'Chelsea',
            'Barca'
        ]
    }

    // The constructor cannot be changed
    constructor(){
        return this
    }
}
2 Answers

The Array.from method converts an iterable object to an array, and the exercise wants you to implement the iterable protocol on the TeamsCollection:

class TeamsCollection {
    get teams() {
        return ['Liverpool', 'Chelsea', 'Barca']
    }

    *[Symbol.iterator]() {
        yield* this.teams.reverse(); // or write a decrement loop that yields the elements
    }
}

you should overWrite from function.

class TeamsCollection {
    get teams() {
        return [
            'Liverpool',
            'Chelsea',
            'Barca'
        ]
    }

    // The constructor cannot be changed! Do not edit!
    constructor(){
        return this
    }
}

var oldFrom = Array.from;
Array.from = function(obj , mapFunc ) {
  if(obj && Array.isArray(obj.teams)) {
    if(mapFunc) {
      return obj.teams.map(mapFunc);
    }
    return obj.teams
  }
  return oldFrom(obj , mapFunc)
}

console.log(Array.from(new TeamsCollection()).join(","))
console.log(Array.from([1,2,3]).join(","))
Related