UNPKG

eliza-core

Version:

A rendition of ELIZA program engine by Weizenbaum sharable for all javascript environments

56 lines (55 loc) 1.78 kB
import * as estring from './estring'; import { UnexpectedNumberException } from './exceptions'; export class Reassemble { constructor($template, $decompose, $annotate) { this.template = $template; this.decompose = $decompose; this.annotate = $annotate; } isAnnotated() { return !!this.annotate; } getAnnotate() { if (!this.annotate) { throw new Error('This Reassemble is not annotated'); } return this.annotate; } getTemplate() { return this.template; } assemble(decomposedTokens) { let ruleTemplate = this.template; do { const lines = estring.match(ruleTemplate, 'goto *'); if (lines && lines[0]) { return { gotoKey: lines[0], }; } } while (0); let work = ''; do { if (estring.match(ruleTemplate, '(#)*')) { ruleTemplate = ' ' + ruleTemplate; continue; } const lines = estring.match(ruleTemplate, '* (#)*'); if (!lines) { break; } ruleTemplate = lines[2]; const n = parseInt(lines[1], 10) - 1; if (isNaN(n)) { throw new UnexpectedNumberException(lines[1], 'reassembly'); } if (n < 0 || n > decomposedTokens.length) { throw new Error(`Fatal Error: Substitution number is bad ${lines[1]} in ${this.getTemplate}`); } const term = decomposedTokens[n]; work += `${lines[0]} ${term}`; } while (true); work += ruleTemplate; return { result: work, annotation: this.annotate }; } }