From cd0496a690422fd966cfa152fa2de1de09d08fb3 Mon Sep 17 00:00:00 2001 From: Kayne Ruse Date: Thu, 13 Jun 2019 11:57:17 +1000 Subject: [PATCH] Added replacement.js --- common/replacement.js | 60 +++++++++++++++++++++++++++++ public/{index.html => index.html.t} | 4 +- server/index.js | 9 ++++- server/website_descriptions.json | 6 +++ 4 files changed, 75 insertions(+), 4 deletions(-) create mode 100644 common/replacement.js rename public/{index.html => index.html.t} (90%) create mode 100644 server/website_descriptions.json diff --git a/common/replacement.js b/common/replacement.js new file mode 100644 index 0000000..592073d --- /dev/null +++ b/common/replacement.js @@ -0,0 +1,60 @@ +//replacement(options)(key [, args...]) +//options - the json object containing all options +//key - one of the keys in options +//data (optional) - a number of arguments that are substituted into the resulting string +const replacement = (options) => (key, ...data) => { + let result; + + //randomize arrays + if (Array.isArray(options[key])) { + result = options[key][Math.floor(Math.random() * options[key].length)]; + } else { + result = options[key]; + } + + //handle no result + if (result === undefined) { + const noResult = options["noResult"]; + if (noResult === undefined) { + return ""; //nothing at all to show + } + //randomized noResult array + if (Array.isArray(noResult)) { + result = noResult[Math.floor(Math.random() * noResult.length)]; + } else { + result = noResult; + } + } + + //replacement engine + let counter = 0; + data.map((dat) => { + counter++; + result = result.replace(/\{([1-9][0-9]*)\}/g, a => a === "{" + counter + "}" ? dat : a); + }); + + //return the final result + return result; +}; + +//templateReplacement(templateString [, args...]) +//templateString - the string to act as a template +//data (optional) - a number of arguments that are substituted into the template string +const stringReplacement = (templateString, ...data) => { + let result = templateString; + + //replacement engine + let counter = 0; + data.map((dat) => { + counter++; + result = result.replace(/\{([1-9][0-9]*)\}/g, a => a === "{" + counter + "}" ? dat : a); + }); + + //return the final result + return result; +} + +module.exports = { + replacement: replacement, + stringReplacement: stringReplacement +}; \ No newline at end of file diff --git a/public/index.html b/public/index.html.t similarity index 90% rename from public/index.html rename to public/index.html.t index 2fbdf4a..56c0950 100644 --- a/public/index.html +++ b/public/index.html.t @@ -7,7 +7,7 @@ Kingdom Battles! - +