简体   繁体   中英

JavaScript: Create Factory Function that Returns Object with Methods That Have Specific Properties

I have a factory function that returns an object. Within the object, I have a method called getNext.

I want the getNext method to return an object with the properties value and done .

Below is my code but it appears that what I have within the return brackets is incorrect.

function makeIterator (arr){

  let methodCalls = 0; 

    return {
      getNext(obj){
        methodCalls += 1; 

        return {
          this.value = ''; 
          this.done = ''; 
        }
      },

      getIndex(){
        return methodCalls
      }
    }
  }

My code above does not pass the testspec below:

it('the `getNext` method returns an object with the properties `value` and `done`', () => {
    const iterator = makeIterator(['first', 'second', 'third']);
    const iterableInfo = iterator.getNext();

expect(Object.keys(iterableInfo).sort()).toEqual(['done', 'value'].sort());
    expect(iterableInfo.hasOwnProperty('value')).toBe(true);
    expect(iterableInfo.hasOwnProperty('done')).toBe(true);
  });

What am I doing wrong?

It seems as if you are trying to utilize destructuring assignment .

Here's an example of what it would look like:

var a, b, rest;
[a, b] = [10, 20];

More info here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM