diff --git a/src/operator.test.ts b/src/operator.test.ts new file mode 100644 index 0000000..13879da --- /dev/null +++ b/src/operator.test.ts @@ -0,0 +1,21 @@ +import { isStandardFunction, standardFunctions } from './operators'; + +describe('Operators tests', () => { + describe('isStandardFunction', () => { + it('should return true for standard functions', () => { + expect(Object.keys(standardFunctions).every(isStandardFunction)).toBeTruthy(); + }); + it('should return false for non standard function', () => { + const nonStandardFunctions = [ + 'toString', + 'valueOf', + 'toLocaleString', + 'hasOwnProperty', + 'isPrototypeOf', + 'propertyIsEnumerable', + 'constructor', + ]; + expect(Object.keys(nonStandardFunctions).every(isStandardFunction)).toBeFalsy(); + }); + }); +}); diff --git a/src/operators.ts b/src/operators.ts index 31fde54..bcb3b3c 100644 --- a/src/operators.ts +++ b/src/operators.ts @@ -179,3 +179,7 @@ export const standardFunctions = { }`, keys: 'function keys(obj) { return Object.keys(obj); }', }; + +export function isStandardFunction(name: string): boolean { + return Object.prototype.hasOwnProperty.call(standardFunctions, name); +} diff --git a/src/translator.ts b/src/translator.ts index 5842b99..cb6dc35 100644 --- a/src/translator.ts +++ b/src/translator.ts @@ -7,7 +7,7 @@ import { VARS_PREFIX, } from './constants'; import { JsonTemplateTranslatorError } from './errors'; -import { binaryOperators, standardFunctions } from './operators'; +import { binaryOperators, isStandardFunction, standardFunctions } from './operators'; import { ArrayExpression, AssignmentExpression, @@ -514,7 +514,7 @@ export class JsonTemplateTranslator { } const functionArgsStr = this.translateSpreadableExpressions(expr.args, result, code); const functionName = this.getFunctionName(expr, result); - if (expr.id && standardFunctions[expr.id]) { + if (expr.id && isStandardFunction(expr.id)) { this.standardFunctions[expr.id] = standardFunctions[expr.id]; code.push(`if(${functionName} && typeof ${functionName} === 'function'){`); code.push(result, '=', functionName, '(', functionArgsStr, ');'); diff --git a/test/scenarios/functions/data.ts b/test/scenarios/functions/data.ts index e582341..556b19e 100644 --- a/test/scenarios/functions/data.ts +++ b/test/scenarios/functions/data.ts @@ -15,7 +15,7 @@ export const data: Scenario[] = [ }, { templatePath: 'js_date_function.jt', - output: [2022, 8, 19], + output: ['2022', 8, 19], }, { templatePath: 'new_operator.jt', diff --git a/test/scenarios/functions/js_date_function.jt b/test/scenarios/functions/js_date_function.jt index 2f1b301..93b2e75 100644 --- a/test/scenarios/functions/js_date_function.jt +++ b/test/scenarios/functions/js_date_function.jt @@ -1,2 +1,2 @@ const date = new Date('2022-08-19'); -[date.getFullYear(), date.getMonth() + 1, date.getDate()]; +[date.getFullYear().toString(), date.getMonth() + 1, date.getDate()];