| 509 | * @returns Approximate size in bytes |
| 510 | */ |
| 511 | export function estimateSize(obj: unknown): number { |
| 512 | const seen = new WeakSet(); |
| 513 | |
| 514 | function sizeOf(value: unknown): number { |
| 515 | if (value === null || value === undefined) { |
| 516 | return 0; |
| 517 | } |
| 518 | |
| 519 | switch (typeof value) { |
| 520 | case 'boolean': |
| 521 | return 4; |
| 522 | case 'number': |
| 523 | return 8; |
| 524 | case 'string': |
| 525 | return 2 * (value as string).length; |
| 526 | case 'object': |
| 527 | if (seen.has(value as object)) { |
| 528 | return 0; |
| 529 | } |
| 530 | seen.add(value as object); |
| 531 | |
| 532 | if (Array.isArray(value)) { |
| 533 | return value.reduce((acc: number, item) => acc + sizeOf(item), 0); |
| 534 | } |
| 535 | |
| 536 | return Object.entries(value as object).reduce( |
| 537 | (acc, [key, val]) => acc + sizeOf(key) + sizeOf(val), |
| 538 | 0 |
| 539 | ); |
| 540 | default: |
| 541 | return 0; |
| 542 | } |
| 543 | } |
| 544 | |
| 545 | return sizeOf(obj); |
| 546 | } |
| 547 | |
| 548 | /** |
| 549 | * Memory monitor for tracking usage during operations |