Skip to content
Onsite

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-1 and has a length of n. Every argument is an item, so new MyArray(3) holds the single item 3 (it does not create an empty array of length 3).
  • MyArray.prototype must inherit from Array.prototype, so instances get the built-in array methods (push, pop, join, indexOf, slice, includes, ...) without you copying them. Instances are instanceof MyArray and instanceof Array.
  • MyArray.prototype.constructor must be MyArray.
  • Add three methods on MyArray.prototype (shared, not copied onto each instance): first() and last() return the first or last item (undefined when empty), and sum() returns the sum of the items (0 when 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

Run checks the 3 visible tests, Submit all 9.