Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

sentence-engine

sindrekjr89Unlicense0.8.0TypeScript support: included

Sentence generator focused on versatility and user control.

sentence, sentences, sentence-generator, text-generator, template-engine, template, vocabulary, random

readme

Sentence Engine

npm version build

An easy-to-use sentence generator running on Node.js. It takes a template and vocabulary freely defined by the user.

Features

TypeScript

Written in TypeScript; compiles to ES2019 Javascript.

Full User Control

Focused on versatility, where templates and vocabulary should be fully customizable by the user.

Resolvable Strings

Templates and vocabularies are able to handle both normal strings and functions that return strings. See the Types section for examples.

Lightweight and object-oriented

Usage is simple with createSentence and configure, while underlying classes Sentence and SentenceFactory allow for more customizability.

Usage

createSentence(templates, vocabulary, options) => Sentence

const { createSentence } = require('sentence-engine');

const someTemplate = '{example} template.';
const someVocabulary = {
  example: ['example', 'default', 'useless'],
};

const anInstanceOfTheSentenceClass = createSentence(someTemplate, someVocabulary, { capitalize: true }); 
//    ^ Sentence { value: 'Useless template.' }
const { value } = anInstanceOftheSentenceClass;
//      ^ string

createSentence can be considered the default entry point, and yields a Sentence object when given a template and a vocabulary. You can either store the full Sentence object for later use, or immediately deconstruct for the generated value.

configure(config)

const { createSentence, configure } = require('sentence-engine');

configure({
  options: someOptions,
  templates: someTemplates,
  vocabulary: someVocabulary,
});
const { value } = createSentence(); // will use the above configuration by default
const { value } = createSentence(someOtherTemplate); // will use someOtherTemplate

configure may be used to define default values for your templates, vocabulary, and options. If these are defined, they will automatically be provided to any sentence you call for through the default createSentence entry point, unless you provide new arguments to that method.

Sentence

const { Sentence } = require('sentence-engine');

const helloWorldSentence = new Sentence(
  '{greeting}, {noun}',
  { greeting: ['hello'], noun: ['world'] },
);

The Sentence class may be utilized if wanting to control sentence generation at the lowest possible level. See the class implementation here.

SentenceFactory

const { SentenceFactory } = require('sentence-engine');

const mySentenceFactory = new SentenceFactory();

The SentenceFactory class contains all of the functions summaried above as exposed entry functions. The sole purpose of instantiating further factories locally would be to run more than one of them within the same module. For most use cases this is probably not necessary at all. See the class implementation here.

Types

Template

A template is defined as a string or function that returns a string. When templates are asked for, a single template or an array of templates can be given.

Vocabulary

A vocabulary is defined as an object where keys should be string and values should be arrays of strings (or functions that return strings), like so:

const vocabulary = {
  noun: ['table', 'car', 'house', () => 'plate'],
  animal: ['bear', 'cat', 'comodo dragon'],
  smalltalk: [
    'well well well.',
    () => {
      const currentHour = new Date().getHours();
      const isNightTime = currentHour > 21 || currentHour < 6;
      return isNightTime ? 'it\'s a nice night out.' : 'how about that weather?';
    },
  ],
};

Notice that vocabularies may be used very widely, whether formally within terms of adjectives, nouns, etc, or for made-up categories or longer phrases.

Options

Options is defined as an object with the fields listed below.

capitalize: boolean

createSentence(template, vocabulary, { capitalize: true });

If true, generated words will be capitalized when they appear at the start of a string or after a full-stop.

forceNewSentence: boolean

createSentence(template, vocabulary, { forceNewSentence: true });

If true and a new unique sentence is possible, then sentence generation will repeat until one is found.

placeholderNotation: string || placeholderNotation: { start: string, end: string }

createSentence(template, vocabulary, { placeholderNotation: '{ }' });
createSentence(template, vocabulary, { placeholderNotation: { start: '{', end: '}' } });

May be set to change the notation used to detect placeholders to be changed by the templating engine. Note that notation start and end may be defined by space separation or explicit field references (except when manipulating the options object directly on the Sentence class).

preservePlaceholderNotation: boolean

createSentence(template, vocabulary, { preservePlaceholderNotation: true });

If true, then sentence generation will retain the placeholder notation around generated words/phrases.

Contributing

Sure! Feel free to submit PRs or issues.

Background

The package is inspired by the TV show Better Off Ted's episode S2E8 "The Impertence of Communicationizing", and started off as a proof-of-concept for the insult formula introduced in the episode.

changelog

Changelog

0.8.0

25.11.2020

Breaking :boom:

  • Changed return type of Sentence.generate to string

0.7.0

21.11.2020

Breaking :boom:

  • Changed various types and interfaces
  • Removed method restoreDefaults from SentenceFactory

    Features :tada:

  • Added needlessly complex esm build process
  • Added automatic type declarations to compile
  • Added following types to exports:
    • Template Vocabulary Options Configuration StringResolvable WeightedEntry

      Bugfixes :bug:

  • Fixed various issues/bugs with special characters in placeholder notation

0.6.1

Bugfix :bug:

  • Fix error where adding a- or -s to a placeholder would break during runtime

0.6.0 - Weighted Types

24.08.2020

Breaking :boom:

  • Changed method addVocab to addVocabulary in class Sentence
  • Removed method setOptions in class Sentence
  • Removed option allowDuplicates

    Features :tada:

  • Added type WeightedTemplate
  • Added type WeightedVocabulary
  • Added type WeightedEntry
  • Added setter options in Sentence
  • Added getter weightedTemplates in Sentence
  • Added getter weightedVocabulary in Sentence
  • Changed resolution of duplicates so that they simply increases the given entry's weight

    Bugfixes :bug:

  • Fix addVocabulary so that it appends instead of overwriting

0.5.2 - StringResolvable

18.08.2020

Features :tada:

  • Added type StringResolvable
  • Change type Template to accept StringResolvable
  • Change type Vocabulary to accept StringResolvable

0.5.1

17.08.2020

  • :bug: Fix issue where option forceNewSentence would have no effect

0.5.0 - TypeScript

16.08.2020

Breaking :boom:

  • Refactored entire project to TypeScript
  • Removed default export, should now defer to importing createSentence for the default behaviour
  • Removed or changed all other exports

    Features :tada:

  • Added class Sentence to exports
  • Added class SentenceFactory to exports

0.4.2 - 11.08.2020

Documentation

  • :nut_and_bolt: Change package keywords
  • :nut_and_bolt: Change package description
  • :nut_and_bolt: Change README

0.4.1 - 30.07.2020

  • :tada: New option allowDuplicates now functions as expected
  • :tada: New option capitalize now functions as expected
  • :tada: New option placeholderNotation
  • :boom: Changed option preserveCurlyBrackets to preservePlaceholderNotation
  • :bug: Fix setOptions so that it no longer resets unspecified options to previous defaults

0.4.0 - 26.07.2020

Features

  • :tada: New option forceNewSentence, which will force Sentence.generate() to avoid duplicate of previous sentence when possible
  • :tada: New method restoreDefaults() available at entry point

    Development

  • :nut_and_bolt: Add jest for testing
  • :nut_and_bolt: Add eslint for linting
  • :nut_and_bolt: Add .npmignore
  • :nut_and_bolt: Add Github Workflows for CI/CD
  • :nut_and_bolt: Change validation to module validator
  • :nut_and_bolt: Change defaults to module defaults
  • :nut_and_bolt: Various other changes and improvements to readability and encapsulation