| 842 | * @returns Approximate size in bytes |
| 843 | */ |
| 844 | export function estimateSize(obj: unknown): number { |
| 845 | const seen = new WeakSet(); |
| 846 | |
| 847 | function sizeOf(value: unknown): number { |
| 848 | if (value === null || value === undefined) { |
| 849 | return 0; |
| 850 | } |
| 851 | |
| 852 | switch (typeof value) { |
| 853 | case 'boolean': |
| 854 | return 4; |
| 855 | case 'number': |
| 856 | return 8; |
| 857 | case 'string': |
| 858 | return 2 * (value as string).length; |
| 859 | case 'object': |
| 860 | if (seen.has(value as object)) { |
| 861 | return 0; |
| 862 | } |
| 863 | seen.add(value as object); |
| 864 | |
| 865 | if (Array.isArray(value)) { |
| 866 | return value.reduce((acc: number, item) => acc + sizeOf(item), 0); |
| 867 | } |
| 868 | |
| 869 | return Object.entries(value as object).reduce( |
| 870 | (acc, [key, val]) => acc + sizeOf(key) + sizeOf(val), |
| 871 | 0 |
| 872 | ); |
| 873 | default: |
| 874 | return 0; |
| 875 | } |
| 876 | } |
| 877 | |
| 878 | return sizeOf(obj); |
| 879 | } |
| 880 | |
| 881 | /** |
| 882 | * Memory monitor for tracking usage during operations |