Socialify

Folder ..

Viewing memorySize.js
93 lines (85 loc) • 2.3 KB

 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
const ECMA_SIZES = {
  STRING: 2,
  BOOLEAN: 4,
  NUMBER: 8
};

function allProperties(obj) {
  const stringProperties = [];
  for (var prop in obj) {
    stringProperties.push(prop);
  }
  if (Object.getOwnPropertySymbols) {
    var symbolProperties = Object.getOwnPropertySymbols(obj);
    Array.prototype.push.apply(stringProperties, symbolProperties);
  }
  return stringProperties;
}

function sizeOfObject(seen, object) {
  if (object == null) {
    return 0;
  }

  var bytes = 0;
  var properties = allProperties(object);
  for (var i = 0; i < properties.length; i++) {
    var 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;
    }

    var objectType = typeof object;
    switch (objectType) {
      case 'string':
        return object.length * ECMA_SIZES.STRING;
      case 'boolean':
        return ECMA_SIZES.BOOLEAN;
      case 'number':
        return ECMA_SIZES.NUMBER;
      case 'symbol':
        // eslint-disable-next-line no-case-declarations
        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 {*}
 */
export function sizeof(object) {
  return getCalculator(new WeakSet())(object);
}