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); } } }
let n1 = new FooArray(1);.fill()will not work as before. Considernew Array(2).fill(2)andnew Array("hello").fill(2). The latter is what OP is changing the constructor to do.super(...items)they will have that issue.