@javfres/speech-generator
v1.0.5
Published
Text sentences generator with variables, pluralization, random items, and more.
Downloads
6
Readme
Speech generator
This is a javascript library to construct text sentences using a particular grammar that allows to construct templates, variables, choices, random elements...
Usage
I am using typescript, but it should work with plain javascript.
Check src/example.ts
for more examples.
const {SpeechGenerator} = require('@javfres/speech-generator');
const gen = new SpeechGenerator();
gen.add('phrase01', '{person1} is my best friend!');
console.log(gen.render('phrase01',{person1:'John'}));
will output
John is my best friend!
There are several types of 'speeches'
- Template
- Choice
- List
- Function
The template speeches can be composed:
gen.add('phrase02', 'I just want to say that "<phrase01>"');
console.log(gen.render('phrase02',{person1:'John'}));
The variable support dot notation over objects
const john = {name: 'John', lastname: 'Walkers', mail:"[email protected]"};
gen.add('phrase03', 'This last name is {person.lastname} and the email: {person.mail}');
console.log(gen.render('phrase03',{person:john}));
Advanced stuff
Resolve variable from context
{varX}
Include inner speech
<speech>
Random inner speech from the list of choices
<speechA|speechB>
Set variable from speech result to current context
{varX=speech}
Set but do not print
{!varX=speech}
Speech pluralization
<speech(num)>
or <speech(array)>
There is one object for {personA}|There are {num} objects for {personA}
Nothing|One|Many
Speech params (they are written to the current context)
<speech(one=personA,two=personB)>
{one} talks to {two}
Speech params + pluralization
<speech(one=personA,two=personB,num_or_array)>
Opcional speech (will be added if var
is truthy)
<var?speech>
Opcional speech (will be added if var
is falsy)
<!var?speech>
Extra
<var=var2?speech>
<var==100?speech>
Use == for literal
Speech alternative. Renders one of the provided alternatives randomly
gen.addAlternative('alt_speech', "One {x}");
gen.addAlternative('alt_speech', "Two {y}");
gen.addAlternative('alt_speech', ["Three", 'Four']);
// Random alternative with
gen.render('alt_speech');
Special builtin function speeches
- @list
<@list(items)>
- @each
<@each($speech=speechName,$item=person,items)>
- @set
<@set($var=person,var=person)>
,<@set($var=person,oneof=all)>
- @concordance
<@concordance($key=my,var=person)>
- @capitalize
<@capitalize($speech=other)>
Separators for @list
and @each
:
- Include as another parameter:
<@list(items,$sep=and)>
- Types:
and
,cand
,or
,cor
,space
,empty
. - The
ands
andors
are localized usingSpeechGenerator.setLocale('es')
TODO
- [X] Psuedo random in the choices so, not two options can be repeteated
- [X] Add multiple template speechs
- [X] Make $set to root context
- [X] Default name of $set