Skip to content

Commit 32cfb14

Browse files
committed
Add color to subscribe debug logs
1 parent c7ab858 commit 32cfb14

File tree

1 file changed

+28
-17
lines changed

1 file changed

+28
-17
lines changed

src/Event.js

Lines changed: 28 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import chalk from "chalk";
22
import { v4 as uuid } from "uuid";
3+
34
const subscriptions = {};
45
const messages = new Map();
56

@@ -14,12 +15,27 @@ const colors = [
1415
"gray",
1516
];
1617

18+
function typeColor(type) {
19+
const hash = (str) => {
20+
let hash = 0;
21+
for (let i = 0; i < str.length; i++) {
22+
const char = str.charCodeAt(i);
23+
hash = (hash << 5) - hash + char;
24+
hash = hash & hash;
25+
}
26+
return Math.abs(hash);
27+
};
28+
29+
const colorIndex = hash(type) % colors.length;
30+
return colors[colorIndex];
31+
}
32+
1733
const subscribe = (...args) => {
1834
const callback = args.pop();
1935
const type = args.join(".");
2036
const id = uuid();
2137

22-
console.debug("react-event", "subscribe", type, id);
38+
console.debug(chalk[typeColor(type)]("react-event", "subscribe", type, id));
2339

2440
if (!subscriptions[type]) {
2541
subscriptions[type] = {};
@@ -30,7 +46,9 @@ const subscribe = (...args) => {
3046
type,
3147
callback,
3248
unsubscribe: () => {
33-
console.debug("react-event", "unsubscribe", type, id);
49+
console.debug(
50+
chalk[typeColor(type)]("react-event", "unsubscribe", type, id)
51+
);
3452
delete subscriptions[type][id];
3553

3654
if (Object.keys(subscriptions[type]).length === 0) {
@@ -54,20 +72,14 @@ const publish = (...args) => {
5472
const payload = args.pop();
5573
const type = args.join(".");
5674

57-
const hash = (str) => {
58-
let hash = 0;
59-
for (let i = 0; i < str.length; i++) {
60-
const char = str.charCodeAt(i);
61-
hash = (hash << 5) - hash + char;
62-
hash = hash & hash;
63-
}
64-
return Math.abs(hash);
65-
};
66-
67-
const colorIndex = hash(type) % colors.length;
68-
const color = colors[colorIndex];
69-
70-
console.log(chalk[color]("react-event", "publish", type, payload));
75+
console.log(
76+
chalk[typeColor(type)](
77+
"react-event",
78+
"publish",
79+
type,
80+
JSON.stringify(payload)
81+
)
82+
);
7183
messages.set(type, payload);
7284

7385
Object.keys(subscriptions[type] || {}).forEach((key) => {
@@ -88,4 +100,3 @@ function last(type, init) {
88100
}
89101

90102
export { subscribe, publish, messages, last };
91-

0 commit comments

Comments
 (0)