| 818 | * @returns Approximate size in bytes |
| 819 | */ |
| 820 | export function estimateSize(obj: unknown): number { |
| 821 | const seen = new WeakSet(); |
| 822 | |
| 823 | function sizeOf(value: unknown): number { |
| 824 | if (value === null || value === undefined) { |
| 825 | return 0; |
| 826 | } |
| 827 | |
| 828 | switch (typeof value) { |
| 829 | case 'boolean': |
| 830 | return 4; |
| 831 | case 'number': |
| 832 | return 8; |
| 833 | case 'string': |
| 834 | return 2 * (value as string).length; |
| 835 | case 'object': |
| 836 | if (seen.has(value as object)) { |
| 837 | return 0; |
| 838 | } |
| 839 | seen.add(value as object); |
| 840 | |
| 841 | if (Array.isArray(value)) { |
| 842 | return value.reduce((acc: number, item) => acc + sizeOf(item), 0); |
| 843 | } |
| 844 | |
| 845 | return Object.entries(value as object).reduce( |
| 846 | (acc, [key, val]) => acc + sizeOf(key) + sizeOf(val), |
| 847 | 0 |
| 848 | ); |
| 849 | default: |
| 850 | return 0; |
| 851 | } |
| 852 | } |
| 853 | |
| 854 | return sizeOf(obj); |
| 855 | } |
| 856 | |
| 857 | /** |
| 858 | * Memory monitor for tracking usage during operations |