-
Notifications
You must be signed in to change notification settings - Fork 1
/
replacers.ts
34 lines (31 loc) · 930 Bytes
/
replacers.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import { Replacer } from "./types.d.ts";
import { printType } from "./utils.ts";
export const identityReplacer: Replacer = (k, v) => v;
/**
* Prints deep objects only to certain depth
*/
export const maxDepthReplacer = (maxDepth: number): Replacer => {
if (maxDepth === 0) {
return identityReplacer;
}
if (maxDepth === 1) {
return (k, v) =>
k !== `` && v && typeof v === `object` ? printType.call(v) : v;
}
const depthTrack = new Map<Record<string, unknown>, number>();
return function (k, v) {
const currentDepth = depthTrack.get(this) || 0;
if (v && typeof v === `object`) {
if (currentDepth >= maxDepth) {
return printType.call(v);
}
depthTrack.set(v, currentDepth + 1);
}
return v;
};
};
/**
* Add support to serialize ES6 Map
*/
export const serializeMapReplacer: Replacer = (k, v) =>
v && v instanceof Map ? Object.fromEntries(v.entries()) : v;