From 0c709ccd96bd259430a7f8579e02786f45bc7b74 Mon Sep 17 00:00:00 2001 From: Adam Tkaczyk Date: Thu, 14 Mar 2024 23:45:49 +0100 Subject: [PATCH] move and refactor size function --- src/helper.ts | 12 ++++++++++++ src/visitor.ts | 15 +-------------- 2 files changed, 13 insertions(+), 14 deletions(-) diff --git a/src/helper.ts b/src/helper.ts index d099e92..f987cc2 100644 --- a/src/helper.ts +++ b/src/helper.ts @@ -315,3 +315,15 @@ export const getPosition = ( return ctx.children.OpenBracket[0].startOffset } + +export const size = (arr: unknown) => { + if (isString(arr) || isArray(arr)) { + return arr.length + } + + if (isMap(arr)) { + return Object.keys(arr).length + } + + throw new CelEvaluationError(`invalid_argument: ${arr}`) +} diff --git a/src/visitor.ts b/src/visitor.ts index bb19ffb..d85a4f2 100644 --- a/src/visitor.ts +++ b/src/visitor.ts @@ -26,6 +26,7 @@ import { getPosition, getResult, getUnaryResult, + size, } from './helper.js' import { CelEvaluationError } from './index.js' @@ -33,20 +34,6 @@ const parserInstance = new CelParser() const BaseCelVisitor = parserInstance.getBaseCstVisitorConstructor() -const size = (arr: unknown) => { - switch (getCelType(arr)) { - case CelType.list: - case CelType.string: - // @ts-expect-error type assertion error - return arr.length - case CelType.map: - // @ts-expect-error type assertion error - return Object.keys(arr).length - default: - throw new CelEvaluationError(`invalid_argument: ${arr}`) - } -} - export class CelVisitor extends BaseCelVisitor implements ICstNodeVisitor