Skip to content

Commit

Permalink
Change type-check approach (if-else)
Browse files Browse the repository at this point in the history
  • Loading branch information
david0xd committed Jul 12, 2022
1 parent 7a4a1fb commit 44db981
Showing 1 changed file with 16 additions and 33 deletions.
49 changes: 16 additions & 33 deletions src/json.ts
Original file line number Diff line number Diff line change
Expand Up @@ -310,56 +310,39 @@ export function validateJsonAndGetSize(
return [true, skipSizing ? 0 : JsonSize.Null];
}

// Check and calculate sizes for basic types
// eslint-disable-next-line default-case
switch (typeof value) {
case 'function':
return [false, 0];
case 'string':
return [
true,
skipSizing ? 0 : calculateStringSize(value) + JsonSize.Quote * 2,
];
case 'boolean':
if (skipSizing) {
return [true, 0];
}
return [true, value ? JsonSize.True : JsonSize.False];
case 'number':
return [true, skipSizing ? 0 : calculateNumberSize(value)];
}

// Handle specific complex objects that can be serialized properly
// Check and calculate sizes for basic (and some special) types
const typeOfValue = typeof value;
try {
if (value instanceof Date) {
if (skipSizing) {
return [true, 0];
}
if (typeOfValue === 'function') {
return [false, 0];
} else if (typeOfValue === 'string' || value instanceof String) {
return [
true,
// Note: Invalid dates will serialize to null
isNaN(value.getDate())
? JsonSize.Null
: JsonSize.Date + JsonSize.Quote * 2,
skipSizing
? 0
: calculateStringSize(value as string) + JsonSize.Quote * 2,
];
} else if (value instanceof Boolean) {
} else if (typeOfValue === 'boolean' || value instanceof Boolean) {
if (skipSizing) {
return [true, 0];
}
// eslint-disable-next-line eqeqeq
return [true, value == true ? JsonSize.True : JsonSize.False];
} else if (value instanceof Number) {
} else if (typeOfValue === 'number' || value instanceof Number) {
if (skipSizing) {
return [true, 0];
}
return [true, value.toString().length];
} else if (value instanceof String) {
return [true, calculateNumberSize(value as number)];
} else if (value instanceof Date) {
if (skipSizing) {
return [true, 0];
}
return [
true,
calculateStringSize(value.toString()) + JsonSize.Quote * 2,
// Note: Invalid dates will serialize to null
isNaN(value.getDate())
? JsonSize.Null
: JsonSize.Date + JsonSize.Quote * 2,
];
}
} catch (_) {
Expand Down

0 comments on commit 44db981

Please sign in to comment.