-
Notifications
You must be signed in to change notification settings - Fork 0
/
object_length.js
78 lines (72 loc) · 2.36 KB
/
object_length.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
/*jslint node: true */
"use strict";
var _ = require('lodash');
var constants = require('./constants.js');
var PARENT_UNITS_SIZE = 2*44;
var PARENT_UNITS_KEY_SIZE = "parent_units".length;
function getLength(value, bWithKeys) {
if (value === null)
return 0;
switch (typeof value){
case "string":
return value.length;
case "number":
if (!isFinite(value))
throw Error("invalid number: " + value);
return 8;
//return value.toString().length;
case "object":
var len = 0;
if (Array.isArray(value))
value.forEach(function(element){
len += getLength(element, bWithKeys);
});
else
for (var key in value){
if (typeof value[key] === "undefined")
throw Error("undefined at "+key+" of "+JSON.stringify(value));
if (bWithKeys)
len += key.length;
len += getLength(value[key], bWithKeys);
}
return len;
case "boolean":
return 1;
default:
throw Error("unknown type="+(typeof value)+" of "+value);
}
}
function getHeadersSize(objUnit) {
if (objUnit.content_hash)
throw Error("trying to get headers size of stripped unit");
var objHeader = _.cloneDeep(objUnit);
delete objHeader.unit;
delete objHeader.headers_commission;
delete objHeader.payload_commission;
delete objHeader.main_chain_index;
if (objUnit.version === constants.versionWithoutTimestamp)
delete objHeader.timestamp;
delete objHeader.messages;
delete objHeader.parent_units; // replaced with PARENT_UNITS_SIZE
var bWithKeys = (objUnit.version !== constants.versionWithoutTimestamp && objUnit.version !== constants.versionWithoutKeySizes);
return getLength(objHeader, bWithKeys) + PARENT_UNITS_SIZE + (bWithKeys ? PARENT_UNITS_KEY_SIZE : 0);
}
function getTotalPayloadSize(objUnit) {
if (objUnit.content_hash)
throw Error("trying to get payload size of stripped unit");
var bWithKeys = (objUnit.version !== constants.versionWithoutTimestamp && objUnit.version !== constants.versionWithoutKeySizes);
return getLength({ messages: objUnit.messages }, bWithKeys);
}
function getRatio(objUnit) {
try {
if (objUnit.version !== constants.versionWithoutTimestamp && objUnit.version !== constants.versionWithoutKeySizes)
return 1;
return getLength(objUnit, true) / getLength(objUnit);
}
catch (e) {
return 1;
}
}
exports.getHeadersSize = getHeadersSize;
exports.getTotalPayloadSize = getTotalPayloadSize;
exports.getRatio = getRatio;