/**
* @file was in primitive/number
*
* https://stackoverflow.com/questions/40512393/understanding-string-heap-size-in-javascript-v8
* https://stackoverflow.com/questions/26856783/size-of-a-function-in-memory
* https://hashnode.com/post/what-is-the-best-way-to-calculate-the-size-of-a-json-object-in-nodejs-cinklya0f00670d53c0puzb2u
* https://bclary.com/2004/11/07/#a-4.3.16
* https://github.com/miktam/sizeof/blob/master/byte_size.js
* https://github.com/calebsander/structure-bytes
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures
* https://github.com/substack/utf8-length/blob/master/index.js
*/
import { recurse } from '../../deps'
import { ECMA_SIZES } from '../NATIVE/CONSTANTS/NATIVE_SIZES'
import { toKindOf } from '../kind'
import { Kindof } from '../../../typings'
// would be circular :-/ @TODO @FIXME
// const recurse = require('chaintools/recurse')
function toDefaultBytes(x: any): string {
const stringified = JSON.stringify(x)
return ~-encodeURI(stringified).split(/%..|./).length
}
// @TODO should use `is`
function toByteSize(data: any): number {
let size = 0
recurse(data, (value, key, traverse) => {
switch (toKindOf(value)) {
case 'buffer':
size += value.length
break
case 'string':
size += value.length * ECMA_SIZES._STRING
break
case 'boolean':
size += ECMA_SIZES._BOOLEAN
break
case 'number':
size += ECMA_SIZES._NUMBER
break
case 'function':
case 'date':
size += value.toString().length * ECMA_SIZES._STRING
break
case 'undefined':
case 'null':
size += ECMA_SIZES._UNDEFINED
break
default:
size += toDefaultBytes(value)
break
}
})
return size
}
export { toDefaultBytes, toByteSize }
export default toByteSize