Custom Array with Prototype Chain
MediumP3Coding
Build an array-like type with a constructor function and the prototype chain, without using class or extends.
Implement the constructor function MyArray(...items), used as new MyArray(1, 2, 3):
- The new object stores the items at indices
0..n-1and has alengthofn. Every argument is an item, sonew MyArray(3)holds the single item3(it does not create an empty array of length 3). MyArray.prototypemust inherit fromArray.prototype, so instances get the built-in array methods (push,pop,join,indexOf,slice,includes, ...) without you copying them. Instances areinstanceof MyArrayandinstanceof Array.MyArray.prototype.constructormust beMyArray.- Add three methods on
MyArray.prototype(shared, not copied onto each instance):first()andlast()return the first or last item (undefinedwhen empty), andsum()returns the sum of the items (0when empty).
Instances are not real exotic arrays, so Array.isArray(instance) is false; that is expected.
Example 1
- Input
- const a = new MyArray(1, 2, 3); a.push(4); [a.length, a.last(), a.sum(), a.join('-')]
- Output
- [4, 4, 10, '1-2-3-4']
Constraints
- Use a constructor function and prototype assignment, not class syntax.
- 0 <= items.length <= 10^3
Hints
Give it a real attempt first. Run shows which examples fail.
Saved automatically
Run checks the 3 visible tests, Submit all 9. ⌘Enter runs, ⌘⇧Enter submits.