condensed version of console.trace()

谁说我不能喝 提交于 2020-07-09 05:27:48

问题


JavaScript (browser): I want to find out how deep the stack is. Basically, I want to know how many lines would be printed if I would call console.trace(). But I don't want to call console.trace() (and then count lines in the console window), I just want to 'have' that number of lines in a variable which I can then store to get some kind of performance statistics. Here is an example.

function StackTest(limit){
    this.inc = -1;
    this.limit = limit;
}
StackTest.prototype.test = function(n){
    //console.log(n);
    if (n>this.limit){
        console.trace();
        return [n, this.inc];
    }
    this.inc += 2;
    return this.test(n + this.inc);
}
test899 = new StackTest(899);
document.body.innerHTML = test899.test(0);

Above dummy code sums up odd numbers (which generates the sequence of square numbers), until the sum exceeds a given limit, here 899. So, we compute 1 + 3 + 5 + ... + 59 = 900; 900 is the first square exceeding our limit of 899.

The stack depth (for the innermost return) is 30 (as we summed up 30 numbers, namely the odd numbers below 60), and console.trace() will print out 30 lines (to be more exact, 30 lines referring to the last line of our test function)

I want this 30, but I don't want to call console.trace(). Neither do I want to modify my code and put in manual counters. Neither do I want anything specific to the dummy example (like depth = (1+this.inc)/2 or depth=Math.ceil(Math.sqrt(this.limit))); I want a generic way to get the 30 programmatically.

Is that possible?

I should mention: One thing which does not work: generating (not throwing, just creating) an Error with e = new Error('blah'), then doing e.stack, then doing .split('\n') on that to see how many lines there are. The reason this does not work is that the Error stack is 'cut down' to only the topmost couple of lines/frames of the 'real' stack. If there would be something like e.fullStack, that would give me what I want. If error objects as the above have the information I want, then I was unable to find it there.

UPDATE

one more thing which does not work: Error.captureStackTrace, taken from accepted answer to this question. It's 'cut down' also, and therefore, this really shouldn't be the accepted answer!!!

来源:https://stackoverflow.com/questions/62768598/condensed-version-of-console-trace

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!