-
Notifications
You must be signed in to change notification settings - Fork 45
/
index.js
102 lines (90 loc) · 2.63 KB
/
index.js
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
// Copyright 2014 Andrei Karpushonak
'use strict'
const ECMA_SIZES = require('./byte_size')
const Buffer = require('buffer/').Buffer
const isNodePlatform =
typeof process === 'object' && typeof require === 'function'
function allProperties (obj) {
const stringProperties = []
for (const prop in obj) {
stringProperties.push(prop)
}
if (Object.getOwnPropertySymbols) {
const symbolProperties = Object.getOwnPropertySymbols(obj)
Array.prototype.push.apply(stringProperties, symbolProperties)
}
return stringProperties
}
function sizeOfObject (seen, object) {
if (object == null) {
return 0
}
let bytes = 0
const properties = allProperties(object)
for (let i = 0; i < properties.length; i++) {
const key = properties[i]
// Do not recalculate circular references
if (typeof object[key] === 'object' && object[key] !== null) {
if (seen.has(object[key])) {
continue
}
seen.add(object[key])
}
bytes += getCalculator(seen)(key)
try {
bytes += getCalculator(seen)(object[key])
} catch (ex) {
if (ex instanceof RangeError) {
// circular reference detected, final result might be incorrect
// let's be nice and not throw an exception
bytes = 0
}
}
}
return bytes
}
function getCalculator (seen) {
return function calculator (object) {
if (Buffer.isBuffer(object)) {
return object.length
}
const objectType = typeof object
switch (objectType) {
case 'string':
// https://stackoverflow.com/questions/68789144/how-much-memory-do-v8-take-to-store-a-string/68791382#68791382
return isNodePlatform
? 12 + 4 * Math.ceil(object.length / 4)
: object.length * ECMA_SIZES.STRING
case 'boolean':
return ECMA_SIZES.BOOLEAN
case 'number':
return ECMA_SIZES.NUMBER
case 'symbol': {
const isGlobalSymbol = Symbol.keyFor && Symbol.keyFor(object)
return isGlobalSymbol
? Symbol.keyFor(object).length * ECMA_SIZES.STRING
: (object.toString().length - 8) * ECMA_SIZES.STRING
}
case 'object':
if (Array.isArray(object)) {
return object.map(getCalculator(seen)).reduce(function (acc, curr) {
return acc + curr
}, 0)
} else {
return sizeOfObject(seen, object)
}
default:
return 0
}
}
}
/**
* Main module's entry point
* Calculates Bytes for the provided parameter
* @param object - handles object/string/boolean/buffer
* @returns {*}
*/
function sizeof (object) {
return getCalculator(new WeakSet())(object)
}
module.exports = sizeof