实现 sizeOf 函数,传入一个 object,计算这个 Object 占用了多少个 bytes
可以参考:https://github.com/miktam/sizeof
- Number:一个数字 8 字节(64 位存储)
- String:一个字符 2 字节
- Boolean:4 个字节
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
| const same = {} const testData = { a: 111, b: 'ccc', 222: false, c: same, d: same, }
const seen = new WeakSet() function sizeOfObj(obj) { if (obj === null) return 0
let bytes = 0 const props = Object.keys(obj) for (let i = 0; i < props.length; i++) { const key = props[i] bytes += calculator(key) if (typeof obj[key] === 'object' && obj[key] !== null) { if (seen.has(obj[key])) continue seen.add(obj[key]) } bytes += calculator(obj[key]) } return bytes }
function calculator(obj) { const objType = typeof obj switch (objType) { case 'string': return obj.length * 2 case 'boolean': return 4 case 'number': return 8 case 'object': if (Array.isArray(obj)) { return obj.map(calculator).reduce((res, cur) => res + cur, 0) } else { return sizeOfObj(obj) } default: return 0 } } console.log(calculator(testData))
|