@rustable/utils
Version:
Essential utilities for object cloning, string manipulation, and value comparison in TypeScript, inspired by Rust's standard library.
83 lines (80 loc) • 2.16 kB
JavaScript
;
;
class Location {
constructor() {
const stack = new Error().stack?.split("\n").slice(2) || [];
this._stack = stack.map((s) => this.parseStackLine(s));
}
/**
* Parse a single line from the stack trace
*/
parseStackLine(stackLine) {
const reg = /\(([^)]*)\)/g;
const matches = [...stackLine.matchAll(reg)].map((m) => m[1].trim());
let path = matches[matches.length - 1];
if (!path) {
path = stackLine.replace("at", "").trim();
}
const lastSlashIndex = Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\"));
const fileInfo = path.substring(lastSlashIndex + 1).split(":");
const file = fileInfo[0];
const line = parseInt(fileInfo[1]);
const column = parseInt(fileInfo[2]);
let name = stackLine.replace(`(${path})`, "").replace("at", "").trim();
if (path === name) {
name = file;
}
return {
name,
path,
file,
line,
column
};
}
/**
* Gets the caller at a specific depth in the stack
* @param depth Stack depth (0 = current function, 1 = immediate caller, etc.)
* @returns Caller information or undefined if depth exceeds stack size
*
* @example
* ```typescript
* const loc = new Location();
* const immediate = loc.caller(1); // immediate caller
* const deeper = loc.caller(2); // caller's caller
* ```
*/
caller(depth = 1) {
if (depth < 0) {
throw new Error("Depth must be non-negative");
}
return this._stack[depth];
}
/**
* Gets the current location in the code
* @returns Current caller information
*
* @example
* ```typescript
* const loc = new Location();
* const current = loc.current(); // {name: 'currentFunction', ...}
* ```
*/
current() {
return this._stack[0];
}
/**
* Gets all callers in the stack trace
* @returns Array of all callers
*
* @example
* ```typescript
* const loc = new Location();
* const fullStack = loc.getStack(); // [{name: 'current'}, {name: 'caller'}, ...]
* ```
*/
stack() {
return [...this._stack];
}
}
exports.Location = Location;