From cca668c7a38d934f1c38e2dfa9b775c6d4784fb0 Mon Sep 17 00:00:00 2001 From: Mark Stacey Date: Thu, 3 Oct 2024 10:44:35 -0230 Subject: [PATCH] Refactor primitive check and count steps --- shared/modules/sizeof.js | 24 +++++++++++++++--------- 1 file changed, 15 insertions(+), 9 deletions(-) diff --git a/shared/modules/sizeof.js b/shared/modules/sizeof.js index 5acb80023225..882541582aed 100644 --- a/shared/modules/sizeof.js +++ b/shared/modules/sizeof.js @@ -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 @@ -51,12 +55,17 @@ 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; } @@ -64,13 +73,10 @@ export function assertObjectMaxSize(data, maxSize = 0) { 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); } }