UNPKG

@cognigy/rest-api-client

Version:

Cognigy REST-Client

37 lines 1.33 kB
// based on https://github.com/lyroyce/sizeof/blob/master/lib/sizeof.js /** * Calculates the byte size of an object, aborts when the validation limit is hit * @param {Object} object * @param {number} limit The limit which the object cannot exceed */ export const validateObjectSize = (object, limit) => { const objectList = []; const stack = [object]; let bytes = 0; while (stack.length) { const value = stack.pop(); if (typeof value === 'boolean') { bytes += 4; } else if (typeof value === 'string') { bytes += value.length * 2; } else if (typeof value === 'number') { bytes += 8; } else if (typeof value === 'object' && objectList.indexOf(value) === -1) { objectList.push(value); // if the object is not an array, add the sizes of the keys if (Object.prototype.toString.call(value) != '[object Array]') { for (const key in value) bytes += 2 * key.length; } for (const key in value) stack.push(value[key]); } if (limit && bytes > limit) return { valid: false, bytes: null }; } return { valid: true, bytes }; }; //# sourceMappingURL=objectSizeValidator.js.map