JavaScript solution flattening list


  • 0
    H
    var NestedIterator = function(nestedList) {
        this.list = flatten(nestedList);
        this.index = 0;
    };
    
    var flatten = function(nestedList) {
       return nestedList.reduce((prev, cur) =>
            cur.isInteger() ?  
            prev.concat(cur.getInteger()): prev.concat(flatten(cur.getList())), []);
    }
    
    /**
     * @this NestedIterator
     * @returns {boolean}
     */
    NestedIterator.prototype.hasNext = function() {
        return this.index < this.list.length;
    };
    
    /**
     * @this NestedIterator
     * @returns {integer}
     */
    NestedIterator.prototype.next = function() {
        return this.list[this.index++];
    };
    
    /**
     * Your NestedIterator will be called like this:
     * var i = new NestedIterator(nestedList), a = [];
     * while (i.hasNext()) a.push(i.next());
    */
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.