0

I am implementing an extended class from Array with numerical methods such as sum, mean, std, etc.

There is no problem to instantiate an object with zero or 2+ elements, but I can't implement one-element objects using the same approach:

let n0 = new FooArray(); let n0 = new FooArray(1); let n2 = new FooArray(1, 2); 

I started implementing a custom constructor to handle this one-element (code below), but I am not sure this is a good practice since I couldn't use fill method, for instance (new FooArray(2).fill(0)).

class FooArray extends Array { constructor(...items) { if (items.length == 1) { super(); this.push(items[0]); } else { super(...items); } } } 
8
  • 1
    You mean let n1 = new FooArray(1); Commented Jan 15 at 14:27
  • " I couldn't use fill method": I don't see a problem with that example. Commented Jan 15 at 14:30
  • @trincot the problem is that if OP changes the constructor, then the .fill() will not work as before. Consider new Array(2).fill(2) and new Array("hello").fill(2). The latter is what OP is changing the constructor to do. Commented Jan 15 at 14:34
  • The way they wrote it in their question, it sounds as referring to the code they presented here. Of course, if they just do super(...items) they will have that issue. Commented Jan 15 at 14:37
  • 1
    It is not clear what you want. let n0 = new FooArray(); -> []? let n1 = new FooArray(1); -> [1]? let n2 = new FooArray(1, 2); -> [1, 2]? let n3 = new FooArray(3).fill(0) -> [0, 0, 0]? how would fooarray know the difference between FooArray(1) and FooArray(3).fill(0) ? Commented Jan 15 at 14:48

1 Answer 1

4

Passing a single integer argument to the constructor will create an array with that many empty slots. Passing more arguments or one non-integer argument will create an array with those elements as content.

This is not a very good API, hence the Array.of() was added to work consistently. It always creates an array with the arguments as items in it. And you do not need to reinvent it, you can use it directly in your custom array implementation:

class FooArray extends Array { customMethod() { return "custom functionality"; } } const myarray = FooArray.of(42); console.log(myarray.length); console.log(myarray[0]); console.log(myarray); console.log(myarray.customMethod());

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.