Skip to content

Commit

Permalink
refactor: static utils to modules
Browse files Browse the repository at this point in the history
  • Loading branch information
koladilip committed May 24, 2024
1 parent e6309c1 commit 312cad1
Show file tree
Hide file tree
Showing 7 changed files with 121 additions and 125 deletions.
8 changes: 4 additions & 4 deletions src/engine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { JsonTemplateLexer } from './lexer';
import { JsonTemplateParser } from './parser';
import { JsonTemplateTranslator } from './translator';
import { EngineOptions, Expression, FlatMappingAST, FlatMappingPaths } from './types';
import { ConverterUtils, CommonUtils } from './utils';
import { CreateAsyncFunction, convertToObjectMapping } from './utils';

export class JsonTemplateEngine {
private readonly fn: Function;
Expand All @@ -24,7 +24,7 @@ export class JsonTemplateEngine {
templateOrExpr: string | Expression | FlatMappingPaths[],
options?: EngineOptions,
): Function {
return CommonUtils.CreateAsyncFunction(
return CreateAsyncFunction(
DATA_PARAM_KEY,
BINDINGS_PARAM_KEY,
this.translate(templateOrExpr, options),
Expand Down Expand Up @@ -76,12 +76,12 @@ export class JsonTemplateEngine {
}
let templateExpr = template as Expression;
if (Array.isArray(template)) {
templateExpr = ConverterUtils.convertToObjectMapping(this.parseMappingPaths(template));
templateExpr = convertToObjectMapping(this.parseMappingPaths(template));
}
return this.translateExpression(templateExpr);
}

evaluate(data: any, bindings: Record<string, any> = {}): any {
evaluate(data: unknown, bindings: Record<string, unknown> = {}): unknown {
return this.fn(data ?? {}, bindings);
}
}
14 changes: 7 additions & 7 deletions src/parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ import {
TokenType,
UnaryExpression,
} from './types';
import { CommonUtils } from './utils/common';
import { convertToStatementsExpr, getLastElement, toArray } from './utils/common';

export class JsonTemplateParser {
private lexer: JsonTemplateLexer;
Expand Down Expand Up @@ -225,7 +225,7 @@ export class JsonTemplateParser {
let parts: Expression[] = [];
let newParts: Expression[] | undefined;
// eslint-disable-next-line no-cond-assign
while ((newParts = CommonUtils.toArray(this.parsePathPart()))) {
while ((newParts = toArray(this.parsePathPart()))) {
parts = parts.concat(newParts);
if (newParts[0].type === SyntaxType.FUNCTION_CALL_EXPR) {
break;
Expand Down Expand Up @@ -1137,7 +1137,7 @@ export class JsonTemplateParser {
const expr = this.parseBaseExpr();
return {
type: SyntaxType.FUNCTION_EXPR,
body: CommonUtils.convertToStatementsExpr(expr),
body: convertToStatementsExpr(expr),
params: ['...args'],
async: asyncFn,
};
Expand Down Expand Up @@ -1308,7 +1308,7 @@ export class JsonTemplateParser {
return {
type: SyntaxType.FUNCTION_EXPR,
block: true,
body: CommonUtils.convertToStatementsExpr(expr),
body: convertToStatementsExpr(expr),
};
}

Expand Down Expand Up @@ -1342,7 +1342,7 @@ export class JsonTemplateParser {
fnExpr: FunctionCallExpression,
pathExpr: PathExpression,
): FunctionCallExpression | PathExpression {
const lastPart = CommonUtils.getLastElement(pathExpr.parts);
const lastPart = getLastElement(pathExpr.parts);
// Updated
const newFnExpr = fnExpr;
if (lastPart?.type === SyntaxType.SELECTOR) {
Expand Down Expand Up @@ -1401,13 +1401,13 @@ export class JsonTemplateParser {
}

const shouldConvertAsBlock = JsonTemplateParser.pathContainsVariables(newPathExpr.parts);
let lastPart = CommonUtils.getLastElement(newPathExpr.parts);
let lastPart = getLastElement(newPathExpr.parts);
let fnExpr: FunctionCallExpression | undefined;
if (lastPart?.type === SyntaxType.FUNCTION_CALL_EXPR) {
fnExpr = newPathExpr.parts.pop() as FunctionCallExpression;
}

lastPart = CommonUtils.getLastElement(newPathExpr.parts);
lastPart = getLastElement(newPathExpr.parts);
if (lastPart?.type === SyntaxType.PATH_OPTIONS) {
newPathExpr.parts.pop();
newPathExpr.returnAsArray = lastPart.options?.toArray;
Expand Down
12 changes: 6 additions & 6 deletions src/translator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ import {
LoopControlExpression,
Keyword,
} from './types';
import { CommonUtils } from './utils/common';
import { convertToStatementsExpr, escapeStr } from './utils/common';

export class JsonTemplateTranslator {
private vars: string[] = [];
Expand Down Expand Up @@ -390,7 +390,7 @@ export class JsonTemplateTranslator {
const valuesCode = JsonTemplateTranslator.returnObjectValues(ctx);
code.push(`${dest} = ${valuesCode}.flat();`);
} else if (prop) {
const propStr = CommonUtils.escapeStr(prop);
const propStr = escapeStr(prop);
code.push(`if(${ctx} && Object.prototype.hasOwnProperty.call(${ctx}, ${propStr})){`);
code.push(`${dest}=${ctx}[${propStr}];`);
code.push('} else {');
Expand Down Expand Up @@ -418,7 +418,7 @@ export class JsonTemplateTranslator {
const result = this.acquireVar();
code.push(JsonTemplateTranslator.generateAssignmentCode(result, '[]'));
const { prop } = expr;
const propStr = CommonUtils.escapeStr(prop?.value);
const propStr = escapeStr(prop?.value);
code.push(`${ctxs}=[${baseCtx}];`);
code.push(`while(${ctxs}.length > 0) {`);
code.push(`${currCtx} = ${ctxs}.shift();`);
Expand Down Expand Up @@ -454,7 +454,7 @@ export class JsonTemplateTranslator {
}
const fnExpr: FunctionExpression = {
type: SyntaxType.FUNCTION_EXPR,
body: CommonUtils.convertToStatementsExpr(...expr.statements),
body: convertToStatementsExpr(...expr.statements),
block: true,
};
return this.translateExpr(fnExpr, dest, ctx);
Expand Down Expand Up @@ -558,7 +558,7 @@ export class JsonTemplateTranslator {

private getSimplePathSelector(expr: SelectorExpression, isAssignment: boolean): string {
if (expr.prop?.type === TokenType.STR) {
return `${isAssignment ? '' : '?.'}[${CommonUtils.escapeStr(expr.prop?.value)}]`;
return `${isAssignment ? '' : '?.'}[${escapeStr(expr.prop?.value)}]`;
}
return `${isAssignment ? '' : '?'}.${expr.prop?.value}`;
}
Expand Down Expand Up @@ -703,7 +703,7 @@ export class JsonTemplateTranslator {

private translateLiteral(type: TokenType, val: any): string {
if (type === TokenType.STR) {
return CommonUtils.escapeStr(val);
return escapeStr(val);
}
return String(val);
}
Expand Down
2 changes: 1 addition & 1 deletion src/utils/common.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { EMPTY_EXPR } from '../constants';
import { SyntaxType } from '../types';
import { CommonUtils } from './common';
import * as CommonUtils from './common';

describe('Common Utils tests', () => {
describe('toArray', () => {
Expand Down
52 changes: 25 additions & 27 deletions src/utils/common.ts
Original file line number Diff line number Diff line change
@@ -1,36 +1,34 @@
import { Expression, StatementsExpression, SyntaxType } from '../types';
import { type Expression, type StatementsExpression, SyntaxType } from '../types';

export class CommonUtils {
static toArray(val: any): any[] | undefined {
if (val === undefined || val === null) {
return undefined;
}
return Array.isArray(val) ? val : [val];
export function toArray(val: any): any[] | undefined {
if (val === undefined || val === null) {
return undefined;
}
return Array.isArray(val) ? val : [val];
}

static getLastElement<T>(arr: T[]): T | undefined {
if (!arr.length) {
return undefined;
}
return arr[arr.length - 1];
export function getLastElement<T>(arr: T[]): T | undefined {
if (!arr.length) {
return undefined;
}
return arr[arr.length - 1];
}

static convertToStatementsExpr(...expressions: Expression[]): StatementsExpression {
return {
type: SyntaxType.STATEMENTS_EXPR,
statements: expressions,
};
}
export function convertToStatementsExpr(...expressions: Expression[]): StatementsExpression {
return {
type: SyntaxType.STATEMENTS_EXPR,
statements: expressions,
};
}

static CreateAsyncFunction(...args) {
// eslint-disable-next-line @typescript-eslint/no-empty-function, func-names
return async function () {}.constructor(...args);
}
export function CreateAsyncFunction(...args) {
// eslint-disable-next-line @typescript-eslint/no-empty-function, func-names
return async function () {}.constructor(...args);
}

static escapeStr(s?: string): string {
if (typeof s !== 'string') {
return '';
}
return `'${s.replace(/\\/g, '\\\\').replace(/'/g, "\\'")}'`;
export function escapeStr(s?: string): string {
if (typeof s !== 'string') {
return '';
}
return `'${s.replace(/\\/g, '\\\\').replace(/'/g, "\\'")}'`;
}
14 changes: 7 additions & 7 deletions src/utils/converter.test.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
/* eslint-disable sonarjs/no-duplicate-string */
import { DATA_PARAM_KEY } from '../constants';
import { PathType, SyntaxType, TokenType } from '../types';
import { ConverterUtils } from './converter';
import { convertToObjectMapping } from './converter';
import { JsonTemplateEngine } from '../engine';

describe('Converter Utils Tests', () => {
describe('convertToObjectMapping', () => {
it('should convert single simple flat mapping to object mapping', () => {
const objectMapping = ConverterUtils.convertToObjectMapping(
const objectMapping = convertToObjectMapping(
JsonTemplateEngine.parseMappingPaths([
{
input: '.a.b',
Expand Down Expand Up @@ -51,7 +51,7 @@ describe('Converter Utils Tests', () => {
});
});
it('should convert single simple flat mapping with array index to object mapping', () => {
const objectMapping = ConverterUtils.convertToObjectMapping(
const objectMapping = convertToObjectMapping(
JsonTemplateEngine.parseMappingPaths([
{
input: '.a.b',
Expand Down Expand Up @@ -100,7 +100,7 @@ describe('Converter Utils Tests', () => {
});
});
it('should convert single flat array mapping to object mapping', () => {
const objectMapping = ConverterUtils.convertToObjectMapping(
const objectMapping = convertToObjectMapping(
JsonTemplateEngine.parseMappingPaths([
{
input: '.a[*].b',
Expand Down Expand Up @@ -155,7 +155,7 @@ describe('Converter Utils Tests', () => {
});
});
it('should convert multiple flat array mapping to object mapping', () => {
const objectMapping = ConverterUtils.convertToObjectMapping(
const objectMapping = convertToObjectMapping(
JsonTemplateEngine.parseMappingPaths([
{
input: '.a[*].b',
Expand Down Expand Up @@ -229,7 +229,7 @@ describe('Converter Utils Tests', () => {
});
});
it('should convert multiple flat array mapping to object mapping with root level mapping', () => {
const objectMapping = ConverterUtils.convertToObjectMapping(
const objectMapping = convertToObjectMapping(
JsonTemplateEngine.parseMappingPaths([
{
input: '~j $.root',
Expand Down Expand Up @@ -326,7 +326,7 @@ describe('Converter Utils Tests', () => {
});
});
it('should convert multiple flat nested array mapping to object mapping with root level mapping', () => {
const objectMapping = ConverterUtils.convertToObjectMapping(
const objectMapping = convertToObjectMapping(
JsonTemplateEngine.parseMappingPaths([
{
input: '~j $.root',
Expand Down
Loading

0 comments on commit 312cad1

Please sign in to comment.