Skip to content

Instantly share code, notes, and snippets.

@jaimerson
Created October 28, 2019 19:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jaimerson/4ce611c1f1f07cea707456d9f3010200 to your computer and use it in GitHub Desktop.
Save jaimerson/4ce611c1f1f07cea707456d9f3010200 to your computer and use it in GitHub Desktop.
class Result{
constructor(public title: string, public imagePath: string) { }
}
class Sentence{
base: string;
values: string[];
results: { [id: string]: Result };
constructor(base: string, values: string[], results: { [id: string]: Result }) {
this.runValidations(base, values, results);
this.base = base;
this.values = values;
this.results = results;
}
resultFor(values: string[]): Result {
let resultStr: string = this.base
values.forEach((v) => {
resultStr = resultStr.replace(/{}/, v);
});
let result = this.results[resultStr]
if (result) {
return result;
} else {
throw `Undefined result for "${resultStr}"`;
}
}
private runValidations(base: string, values: string[], results: { [a: string]: any}) {
let numberOfPlaceholders: number = (base.match(/{}/g) || []).length
if (numberOfPlaceholders < 2) { throw "Must have at least two placeholders."; }
if (values.length != numberOfPlaceholders) { throw `Expected ${numberOfPlaceholders} values, got ${values.length}.`; }
if (Object.keys(results).length != this.factorial(numberOfPlaceholders)) {
throw `Expected ${this.factorial(numberOfPlaceholders)} values, got ${Object.keys(results).length}`;
}
}
private factorial(n : number) : number {
let rval=1;
for (let i = 2; i <= n; i++)
rval = rval * i;
return rval;
}
}
let sentence = new Sentence(
"O {} atropelou o {}",
["carro", "menino"],
{
"O carro atropelou o menino": new Result("O carro atropelou o menino", "http://placekitten.com/200/300"),
"O menino atropelou o carro": new Result("O menino atropelou o carro", "http://placekitten.com/300/200")
}
);
console.log(sentence.resultFor(["menino", "carro"]))
console.log(sentence.resultFor(["carro", "menino"]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment