DaShaman
DaShaman

Reputation: 157

Trying to recreate the array.length method

Like the title says, I am trying to recreate the array.length method and store it as a method on an object. The problem is that I can't seem to figure out how to set the length property to zero... I get this error that says

"should have a 'length' property that is initially 0"

and...

"Error: expected [Function] to equal 0".

I have included the test case below as to how the function is evaluated.

describe('Arrays/Errays', () => {
  let array, contents;

  beforeEach(() => {
    array = new Erray();
    contents = array.contents;
  });

  it('should have a \'length\' property that is initially 0', () => {
      expect(array.length).to.not.be(undefined);
      expect(array.length).to.be(0);
    })
  });

This is what I have coded so far.

function Erray() {
    this.contents = [];
    length: 0;
  }

Erray.prototype.length = function() {
      let length = 0;
      for (let i = 0; i < this.contents.length; i++) {
        length++;
      }
      return length;
    }
  
var array = new Erray;

The second error leads me to believe a function is being returned to the test case and that is why it says "Error: expected [Function] to equal 0" with the word 'Function' in the brackets.

Any clues or tips as to why I am not passing my test case? Thank you for your time!

Upvotes: 1

Views: 201

Answers (1)

Unmitigated
Unmitigated

Reputation: 89497

You can use Object.defineProperty to create a getter for the length property.

function Erray() {
  this.contents = [];
}
Object.defineProperty(Erray.prototype, 'length', {
  get() {
    return this.contents.length;
  }
});
var array = new Erray;
console.log(array.length);
array.contents.push(1);
console.log(array.length);

Upvotes: 1

Related Questions