Skip to content

Commit

Permalink
Merge pull request #75 from streamich/debug
Browse files Browse the repository at this point in the history
`@debug` decorator
  • Loading branch information
streamich authored Nov 1, 2024
2 parents 593bb72 + a40c08a commit d519eba
Show file tree
Hide file tree
Showing 4 changed files with 43 additions and 1 deletion.
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,11 @@ Useful TypeScript utilities.

---

- `@debug` — a class method or function decorator, which logs
the input and output of the function in non-production environments.

---

- `hash` — a fast and simple utility, which hashes a string to an integer. Useful
for generating a shard index of a record based on its ID.

Expand Down
2 changes: 1 addition & 1 deletion src/__bench__/lru.bench.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ const caches: Cache[] = [
create: (limit: number) => lru(limit),
},
];
const limits = [10, 100, 1000, 10000];
const limits = [10, 100, 1000, 10000, 100000];
// const iterations = [10, 100, 1000, 10000];
const iterations = [1000000];
// const reads = [true, false];
Expand Down
36 changes: 36 additions & 0 deletions src/debug.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/* tslint:disable no-invalid-this no-console */

let id = 0;

export function debug<This, Args extends any[], Return>(name?: string) {
return (
fn: (this: This, ...args: Args) => Return,
context?: ClassMethodDecoratorContext<This, (this: This, ...args: Args) => Return>,
) => {
if (process.env.NODE_ENV !== 'production') {
return function (this: This, ...args: Args): Return {
id++;
const idStr = id.toString(36);
const currentName =
name ?? (this ? this.constructor?.name + '.' : '') + (String(context?.name) ?? fn.name ?? 'anonymous');
console.log('%cRUN', 'background:white;color:blue', idStr, currentName, ...args);
try {
const res = fn.apply(this, args);
if (res instanceof Promise) {
res.then(
(res) => console.log('%cSUC', 'background:green;color:white', idStr, currentName, res),
(err) => console.log('%cERR', 'background:red;color:white', idStr, currentName, err),
);
return res;
}
console.log('%cSUC', 'background:green;color:white', idStr, currentName, res);
return res;
} catch (err) {
console.log('%cERR', 'background:red;color:white', idStr, currentName, err);
throw err;
}
};
}
return fn;
};
}
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ export * from './concurrency';
export {once} from './once';
export {concurrency as concurrencyDecorator} from './concurrencyDecorator';
export * from './dataUri';
export * from './debug';
export * from './Defer';
export * from './fanout';
export * from './go';
Expand Down

0 comments on commit d519eba

Please sign in to comment.