Js - solving challenge Range Sum Query - Immutable with creating object and its properties

252 Views Asked by At

I was going through the problems on leetcode site, and saw a problem that I don't know how to approach. This is how they explain it:

Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.

Example: Given nums = [-2, 0, 3, -5, 2, -1]

sumRange(0, 2) -> 1 sumRange(2, 5) -> -1 sumRange(0, 5) -> -3 Note: You may assume that the array does not change. There are many calls to sumRange function.

And this is the code:

/**
 * @param {number[]} nums
 */
var NumArray = function(nums) {
   this.nums = nums;
};

/** 
 * @param {number} i 
 * @param {number} j
 * @return {number}
 */
NumArray.prototype.sumRange = function(i, j) {
    let sum = 0;
    for (i; i <= j; i++) {
        sum += this[i];
    }
    return sum;
};

/** 
 * Your NumArray object will be instantiated and called as such:
 * var obj = Object.create(NumArray).createNew(nums)
 * var param_1 = obj.sumRange(i,j)
 */

What I don't know how to do is, or what exactly it means is this part:

var obj = Object.create(NumArray).createNew(nums)

Am I suppose to create a property createNew that takes mums and creats and array, and why should I do that if the nums are already sent as an array?

1

There are 1 best solutions below

1
On BEST ANSWER

what exactly it means is this part:

var obj = Object.create(NumArray).createNew(nums)

They messed it up and meant simply var obj = new NumArray(nums) (which still is unnecessarily complicated for a functional language like JS).

Apparently the description was changed at some point by someone clueless, as all the old JavaScript submissions in the discussion section (e.g. this one) have the correct code in the comment.