forked from bahmutov/code-snippets
-
Notifications
You must be signed in to change notification settings - Fork 0
/
keys-vs-values.js
60 lines (53 loc) · 1.4 KB
/
keys-vs-values.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
// measures how much memory object keys take vs values in collection of objects
(function keysVsValuesInit(root) {
function stringSize(str) {
// JavaScript strings are unicode UTF-16 up to 2 bytes per character
return str.length * 2;
}
function objectSize(obj) {
if (typeof obj === 'string') {
return stringSize(obj);
}
return stringSize(JSON.stringify(obj));
}
function values(obj) {
return Object.keys(obj).map(function (key) {
return obj[key];
});
}
function listSize(values) {
return values.reduce(function (total, value) {
return objectSize(value) + total;
}, 0);
}
function keysValues(obj) {
if (typeof obj === 'object') {
return {
keys: stringSize( Object.keys(obj).join('') ),
values: listSize( values(obj) )
};
} else {
return {
keys: 0,
values: objectSize(obj)
};
}
}
function keysVsValues(items) {
if (!Array.isArray(items) && typeof items === 'object') {
return keysVsValues([items]);
}
console.assert(Array.isArray(items));
return items.reduce(function (sizes, item) {
var size = keysValues(item);
sizes.keys += size.keys;
sizes.values += size.values;
return sizes;
}, {
keys: 0,
values: 0
});
}
root.keysVsValues = keysVsValues;
console.log('try keysVsValues(<array of objects>);');
}(this));