Skip to content

Commit

Permalink
馃殌 Better string replacement (deploy)
Browse files Browse the repository at this point in the history
  • Loading branch information
barbarbar338 committed Jul 6, 2022
1 parent 8bdbfeb commit 020421d
Showing 1 changed file with 15 additions and 22 deletions.
37 changes: 15 additions & 22 deletions libs/localeParser.ts
@@ -1,11 +1,12 @@
import { useRouter } from "next/router";

import en from "@locales/en.yaml";
import tr from "@locales/tr.yaml";
import constants from "@locales/constants.yaml";
import { useRouter } from "next/router";
import { CONFIG } from "./config";

export interface IToken {
start: RegExp;
end: RegExp;
key: string;
value: string;
}

Expand All @@ -16,57 +17,49 @@ export interface ITokens {
const locales = { en, tr };
const tokens: ITokens = {
purple: {
start: new RegExp("<purple[^>]*>", "gm"),
end: new RegExp("</purple[^>]*>", "gm"),
key: "purple",
value: "<span class='text-purple-500'>",
},
};

class LocaleParser {
private locale: string;

public constants = constants;

constructor(locale = "en") {
this.locale = locale;
}

public get(
name: string,
args?: { [param: string]: string },
): string | string[] {
): string {
const locale = locales[this.locale] || locales["en"];
let str = locale[name];

if (!str)
return `string not found for ${name} in ${
this.locale || "en"
}, please contact the developer.`;
}, please contact the developer with ${CONFIG.EMAIL}.`;

if (args) {
for (const arg in args) {
const regToken = new RegExp(`%{${arg}}`, "gm");

if (Array.isArray(str))
str = str.map((s) => s.replace(regToken, args[arg]));
else str = str.replace(regToken, args[arg]);
str = str.replace(regToken, args[arg] || "ARG_NOT_FOUND");
}
}

if (typeof str == "string") str = this.replaceColors(str);
else if (Array.isArray(str))
str = str.map((s) => this.replaceColors(s));

str = this.replaceColors(str);
str = this.replaceConstants(str);

return str;
}

private replaceConstants(str: string | string[]) {
private replaceConstants(str: string) {
for (const constant in constants) {
const regToken = new RegExp(`%{${constant}}`, "gm");

if (Array.isArray(str))
str = str.map((s) => s.replace(regToken, constants[constant]));
else str = str.replace(regToken, constants[constant]);
str = str.replace(regToken, constants[constant] || "CONSTANT_NOT_FOUND");
}

return str;
Expand All @@ -76,8 +69,8 @@ class LocaleParser {
for (const t in tokens) {
const token = tokens[t];
str = str
.replace(token.start, token.value)
.replace(token.end, "</span>");
.replace(new RegExp(`<${token.key}[^>]*>`, "gm"), token.value)
.replace(new RegExp(`</${token.key}[^>]*>`, "gm"), "</span>");
}

return str;
Expand Down

0 comments on commit 020421d

Please sign in to comment.