function calculater(object) {
const type = typeof object;
switch (type) {
case 'number': {
return 8;
}
case 'string': {
return object.length * 2;
}
case 'boolean': {
return 4;
}
case 'object': {
if (Array.isArray(object)) {
object.map(calculater).reduce(c, b => c + b, 0);
} else {
return sizeofobject(object);
}
}
}
}
let seen = new WeakSet();
function sizeofobject(object) {
if (object === null) {
return 0;
}
let bytes = 0;
const properties = Object.keys(object);
for (let i = 0; i < properties.length; i++) {
const key = properties[i];
if (typeof object[key] === 'object' && object[key] !== null) {
if (seen.has(object[key])) continue;
seen.add(object[key])
}
bytes += calculater(key);
bytes += calculater(object[key]);
}
return bytes
}
const obj = {
name:'liqiu',
age:25
}
console.log(calculater(obj))
网友评论