Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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…

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

"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!

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading