美文网首页
计算字节数

计算字节数

作者: 荔桑 | 来源:发表于2021-04-29 11:29 被阅读0次
    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))
    

    相关文章

      网友评论

          本文标题:计算字节数

          本文链接:https://www.haomeiwen.com/subject/kbdnrltx.html