Skip to content

Commit

Permalink
Exported Parser to OOP Object
Browse files Browse the repository at this point in the history
  • Loading branch information
Reterics committed Oct 14, 2023
1 parent 89fda11 commit 613edcc
Show file tree
Hide file tree
Showing 5 changed files with 55 additions and 23 deletions.
8 changes: 8 additions & 0 deletions src/constants.ts
@@ -0,0 +1,8 @@

export const REGEXPS = {
variable: {
start: "{{",
end: "}}",
regexp: /{{\w*}}/g
}
}
26 changes: 3 additions & 23 deletions src/lejs.ts
Expand Up @@ -23,32 +23,12 @@
'use strict';
import * as fs from 'fs'
import * as path from 'path'
import Parser from "./parsers";

const REGEXPS = {
variable: {
start: "{{",
end: "}}",
regexp: /{{\w*}}/g
}
}


/**
*
* @param {string} string
* @param {object} data
* @param {undefined|object} options
* @returns {*}
*/
export function render (string: string, data, options: object|undefined) {
const config = REGEXPS.variable;
return string.replaceAll(config.regexp, (substr) => {
const variable = substr.substring(config.start.length, substr.length - config.end.length);
if (data && data.hasOwnProperty(variable)) {
return data[variable];
}
return "";
});
const parser = new Parser({cache: false});
return parser.render(string, data);
}

export function renderFile (file: string, data: object|undefined, options: object|undefined) {
Expand Down
21 changes: 21 additions & 0 deletions src/parsers/index.ts
@@ -0,0 +1,21 @@
import {ParserOptions, ParserFunc} from "../types/parsers";
import renderVariable from "./variable";

class Parser {
private parsers: ParserFunc[]
private cache: boolean;
constructor(options: ParserOptions|undefined) {
this.parsers = [
renderVariable
];
this.cache = !!(options && options.cache); // TODO: ROADMAP
}

render(string: string, data: (object | null)) {
return this.parsers.reduce((str, parser) => {
return parser(str, data);
}, string);
}
}

export default Parser;
15 changes: 15 additions & 0 deletions src/parsers/variable.ts
@@ -0,0 +1,15 @@
import {REGEXPS} from "../constants";
import {ParserFunc} from "../types/parsers";


const renderVariable: ParserFunc = (string: string, data: object|null): string => {
const config = REGEXPS.variable;
return string.replaceAll(config.regexp, (substr) => {
const variable = substr.substring(config.start.length, substr.length - config.end.length);
if (data && data.hasOwnProperty(variable)) {
return data[variable];
}
return "";
});
}
export default renderVariable;
8 changes: 8 additions & 0 deletions src/types/parsers.ts
@@ -0,0 +1,8 @@

export interface ParserOptions {
cache?: boolean
}

export interface ParserFunc {
(string: string, data: (object | null)): string
}

0 comments on commit 613edcc

Please sign in to comment.