JavaScript How to limit depth of recursion in JSON.stringify

时间:2016-08-31 12:19:52

标签: javascript recursion

How can I limit the depth of recursion in the function?

2 个答案:

答案 0 :(得分:3)

When creating a recursive function, you can always pass a so called accumulative parameter. Simply pass an extra numeric parameter that you increment each time you enter a new level of recursion (i.e. increment your parameter exactly once each recursive iteration) and pass it through.

You can use this technique for a variety of things, as well as keeping track of the depth of recursion. Simply check the value of the parameter at the start of your function, and return when it is equal to the maximum depth that you wish to traverse into.

Example

This example shows a variable called depthLevel that signifies the level of depth in a tree for the current node. The maxDepthLevel constant should be defined somewhere. This Depth First algorithm will not traverse deeper than maxDepthLevel. Notice how the depthLevel is increased by 1 for each level of recursion, making it an accumulative parameter.

function depthFirst(var node, var depthLevel) {
    if(depthLevel > maxDepthLevel) {
        return;
    }

    //do logic for this node here

    var childrenOfThisNode = node.getChildren();

    foreach(var child in childrenOfThisNode) {
        depthFirst(child, depthLevel + 1)
    }
}

答案 1 :(得分:0)

这是一个简单的函数,当以前见过对象时会插入'...',以防止无限递归。

  function safeStringify (value) {
    const seen = new Set()
    return JSON.stringify(value, (k, v) => {
      if (seen.has(v)) { return '...' }
      if (typeof v === 'object') { seen.add(v) }
      return v
    })
  }