Skip to content

Commit

Permalink
Refactor primitive check and count steps
Browse files Browse the repository at this point in the history
  • Loading branch information
Gudahtt committed Oct 3, 2024
1 parent 21eb563 commit cca668c
Showing 1 changed file with 15 additions and 9 deletions.
24 changes: 15 additions & 9 deletions shared/modules/sizeof.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,10 @@ function getPrimitiveSize(data, dataType) {
}
}

function isPrimitive(data, dataType) {
return data === null || dataType !== 'object';
}

/**
* Main module's entry point
* Calculates Bytes for the provided parameter
Expand All @@ -51,26 +55,28 @@ function getPrimitiveSize(data, dataType) {
*/
export function assertObjectMaxSize(data, maxSize = 0) {
let size = 0;
const topLevelType = typeof data;
if (data === null || topLevelType !== 'object') {
size = getPrimitiveSize(data, topLevelType);

function countPrimitiveSize(value, valueType) {
size += getPrimitiveSize(value, valueType);
if (size > maxSize) {
throw new Error('object exceeded max size');
}
}

const topLevelType = typeof data;
if (isPrimitive(data, topLevelType)) {
countPrimitiveSize(data, topLevelType);
return;
}

const objects = [data];

function countValueSize(value) {
const valueType = typeof value;
if (value !== null && valueType === 'object') {
objects.push(value);
if (isPrimitive(value, valueType)) {
countPrimitiveSize(value, valueType);
} else {
size += getPrimitiveSize(value, valueType);
if (size > maxSize) {
throw new Error('object exceeded max size');
}
objects.push(value);
}
}

Expand Down

0 comments on commit cca668c

Please sign in to comment.