Following the requirement of the code in Leetcode, here is the functional code:
var calculateDepthSum = function (nestedList, depth=1) {
var result = 0;
nestedList.forEach((val) => {
if (val.isInteger() === false) {
result += calculateDepthSum(val.getList(), depth + 1);
} else {
result += val.getInteger() * depth;
}
});
return result;
};
The use of Array.isArray()
is not possible in this case as it will return false for all members. Direct access to values or lists is also prohibited. It is necessary to access them through their API. The function's input is not a simple array; refer to the input type and APIs from the specifications provided below:
* function NestedInteger() {
*
* Return true if this NestedInteger holds a single integer, rather than a nested list.
* @return {boolean}
* this.isInteger = function() {
* ...
* };
*
* Return the single integer that this NestedInteger holds, if it holds a single integer
* Return null if this NestedInteger holds a nested list
* @return {integer}
* this.getInteger = function() {
* ...
* };
*
* Set this NestedInteger to hold a single integer equal to value.
* @return {void}
* this.setInteger = function(value) {
* ...
* };
*
* Set this NestedInteger to hold a nested list and add a nested integer elem to it.
* @return {void}
* this.add = function(elem) {
* ...
* };
*
* Return the nested list that this NestedInteger holds, if it holds a nested list
* Return null if this NestedInteger holds a single integer
* @return {NestedInteger[]}
* this.getList = function() {
* ...
* };
* };
*/
/**
* @param {NestedInteger[]} nestedList
* @return {number}
*/