簡體   English   中英

將遞歸 function 的結果連接到 Javascript 中的數組中的最快方法是什么?

[英]What is the fastest way to concatenate results of a recursive function into an array in Javascript?

正如標題所說,我正在尋找從遞歸 function 創建平面數組 output 的最有效方法。

下面的示例產生了正確的結果,但它有點慢,因為它必須為每個遞歸級別創建一個臨時連接的點數組。

class QuadTree {

  // ...
  // some other methods
  // ...

  get points() {
    if (this.divided) {
      // concatenate and return points of all subtrees
      return this.subtrees[0].points.concat(
        this.subtrees[1].points,
        this.subtrees[2].points,
        this.subtrees[3].points
      );
    }
    // return _points array of this quadtree
    return this._points;
  }
}

有沒有辦法加快這個速度?

我認為這種問題在使用嵌套/樹狀數據結構時很常見,但我還沒有找到令人滿意的解決方案。

我能想到的唯一一件事就是用 function 替換您的訪問器屬性(或者可能在其旁邊添加 function)並傳遞目標數組以便可以直接填充它。 就像是:

class QuadTree {

  // ...
  // some other methods
  // ...

  getDividedPoints(target = []) {
    this.subtrees[0].getDividedPoints(target);
    this.subtrees[1].getDivdedPoints(target);
    this.subtrees[2].getDivdedPoints(target);
    this.subtrees[3].getDivdedPoints(target);
    return target;
  }

  get points() {
    if (this.divided) {
      return this.getDividedPoints([]);
    }
    // return _points array of this quadtree
    return this._points;
  }
}

或者如果subtrees是一個普通數組, getDividedPoints可以是:

getDividedPoints(target = []) {
  this.subtrees.forEach(subtree => subtree.getDividedPoints(target));
  return target;
}

否則,由於我假設您要復制this.subtrees[0].points (而不是插入其中),因此concat會非常好。

如果子樹可能會或可能不會被划分,您將需要 function 中的if 而我才剛剛注意到 class 的名稱。 :-) 所以我可能只打四個電話:

getPoints(target) {
  if (this.divided) {
    target = target || [];
    this.subtrees[0].getPoints(target);
    this.subtrees[1].getPoints(target);
    this.subtrees[2].getPoints(target);
    this.subtrees[3].getPoints(target);
    return target;
  }
  if (target) {
    target.push.apply(target, this._points);
    return target;
  }
  return this._points; // <== If you're really okay with giving this
                       // to the caller (you were in your original code)
}

get points() {
  return this.getDividedPoints([]);
}

...或任何其他關於該基本想法的旋轉。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM