From 380513a0b0a825ba61b1acf2d09953845845f4d3 Mon Sep 17 00:00:00 2001 From: CJ42 Date: Mon, 30 Oct 2023 12:17:32 +0000 Subject: [PATCH] refactor: extract to internal methods --- src/lib/decodeData.ts | 48 ++++++++++++++++++++++--------------------- 1 file changed, 25 insertions(+), 23 deletions(-) diff --git a/src/lib/decodeData.ts b/src/lib/decodeData.ts index 16daead9..a12e4c26 100644 --- a/src/lib/decodeData.ts +++ b/src/lib/decodeData.ts @@ -33,32 +33,41 @@ import { decodeKeyValue, encodeArrayKey } from './utils'; const tupleValueTypesRegex = /bytes(\d+)/; const valueContentsBytesRegex = /Bytes(\d+)/; -export const isValidTuple = (valueType: string, valueContent: string) => { - if (valueType.length <= 2 && valueContent.length <= 2) { +const isValidTupleDefinition = (tupleContent: string): boolean => { + if (tupleContent.length <= 2) { return false; } - - if ( - valueType[0] !== '(' && - valueType[valueType.length - 1] !== ')' && - valueContent[0] !== '(' && - valueContent[valueContent.length - 1] !== ')' - ) { + if (tupleContent[0] !== '(' && tupleContent.at(-1) !== ')') { return false; } - // At this stage, we can assume the user is trying to use a tuple, let's throw errors instead of returning - // false + return true; +}; - let valueTypeToDecode = valueType; +const extractValueTypesFromTuple = (tupleContent: string): string[] => { + let valueTypeToDecode = tupleContent; - if (valueType.includes(COMPACT_BYTES_ARRAY_STRING)) { - valueTypeToDecode = valueType.replace(COMPACT_BYTES_ARRAY_STRING, ''); + if (tupleContent.includes(COMPACT_BYTES_ARRAY_STRING)) { + valueTypeToDecode = tupleContent.replace(COMPACT_BYTES_ARRAY_STRING, ''); } - const valueTypeParts = valueTypeToDecode + return valueTypeToDecode .substring(1, valueTypeToDecode.length - 1) .split(','); +}; + +export const isValidTuple = (valueType: string, valueContent: string) => { + if ( + !isValidTupleDefinition(valueType) || + !isValidTupleDefinition(valueContent) + ) { + return false; + } + + // At this stage, we can assume the user is trying to use a tuple, let's throw errors instead of returning + // false + + const valueTypeParts = extractValueTypesFromTuple(valueType); const valueContentParts = valueContent .substring(1, valueContent.length - 1) @@ -139,15 +148,8 @@ export const decodeTupleKeyValue = ( ): Array => { // We assume data has already been validated at this stage - let valueTypeToDecode = valueType; - - if (valueType.includes('[CompactBytesArray')) { - valueTypeToDecode = valueType.replace(COMPACT_BYTES_ARRAY_STRING, ''); - } + const valueTypeParts = extractValueTypesFromTuple(valueType); - const valueTypeParts = valueTypeToDecode - .substring(1, valueTypeToDecode.length - 1) - .split(','); const valueContentParts = valueContent .substring(1, valueContent.length - 1) .split(',');