Last active
January 4, 2016 01:19
-
-
Save sstur/8547495 to your computer and use it in GitHub Desktop.
Get a stack trace the hard way..
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var stackTrace = (function() { | |
var _toString = Object.prototype.toString; | |
var _slice = Array.prototype.slice; | |
function inArray(array, el) { | |
for (var i = 0, len = array.length; i < len; i++) { | |
if (array[i] === el) return true; | |
} | |
return false; | |
} | |
function Frame(fn) { | |
this._function = fn; | |
this.args = _slice.call(fn['arguments']); | |
} | |
Frame.prototype.getName = function() { | |
var fn = this._function; | |
if (fn.name) { | |
return fn.name; | |
} | |
var definition = fn.toString().split('\n')[0]; | |
var match = definition.match(/^function\s*([^\s(]+)/); | |
return match ? match[1] : 'anonymous'; | |
}; | |
Frame.prototype.toString = function() { | |
var args = []; | |
for (var i = 0, len = this.args.length; i < len; i++) { | |
var arg = this.args[i]; | |
if (typeof arg === 'string') { | |
var str = (arg.length > 50) ? arg.slice(0, 47) + '...' : arg; | |
str = JSON.stringify(str); | |
} else { | |
str = (Object(arg) === arg) ? _toString.call(arg) : '' + arg; | |
} | |
args.push(str); | |
} | |
return this.getName() + '(' + args.join(', ') + ')'; | |
}; | |
function stackTrace() { | |
var seen = []; | |
var stack = []; | |
var fn = stackTrace.caller; | |
while (fn && !inArray(seen, fn)) { | |
seen.push(fn); | |
stack.push(new Frame(fn)); | |
fn = fn.caller; | |
} | |
return stack; | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment