Skip to content

Instantly share code, notes, and snippets.

@IntegerMan
Last active February 20, 2020 05:16
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 IntegerMan/a35508cc5a0bcf66bb772442b2cbcce9 to your computer and use it in GitHub Desktop.
Save IntegerMan/a35508cc5a0bcf66bb772442b2cbcce9 to your computer and use it in GitHub Desktop.
export class Sentence {
public text: string;
constructor() { }
public get verbWord(): Word {
if (this.words.length <= 0 || !this.words[0].isVerb) {
return undefined;
}
return this.words[0];
}
public get verb(): string {
const word = this.verbWord;
if (word) {
return word.reduced;
}
return undefined;
}
public get target(): string | undefined {
if (this.words.length > 1) {
for (const word of this.words) {
if (word.isNoun) {
return word.reduced;
}
}
}
return undefined;
}
public words: Word[] = [];
public get rootWords(): Word[] {
const roots: Word[] = [];
for (const word of this.words) {
if (!word.parent) {
roots.push(word);
}
}
return roots;
}
addWord(word: Word) {
this.words.push(word);
}
public validate(): string | undefined {
if (this.words.length <= 0) {
return 'I\'m sorry, did you want to do something?';
}
if (!this.words[0].isVerb) {
return 'Your command must start with a verb. For example: \'Bark at the squirrel\'';
}
if (this.words.filter(w => w.isVerb).length > 1) {
return 'Your command cannot have more than one verb';
}
return undefined;
}
}
import nlp from 'compromise';
export class Word {
readonly tags: Record<string, boolean>;
public parent: Word;
public children: Word[] = [];
constructor(term: nlp.Term) {
this.text = term.text;
this.reduced = term.reduced;
this.tags = term.tags;
}
public get tagNames(): string[] {
const names: string[] = [];
// tslint:disable-next-line:forin
for (const tag in this.tags) {
if (this.tags.hasOwnProperty(tag)) {
names.push(tag);
}
}
return names;
}
public get hasChildren(): boolean {
return this.children.length > 0;
}
/**
* The raw text the user typed in
*/
public text: string;
/**
* The normalized text for text comparison / matching
*/
public reduced: string;
public get isNoun(): boolean {
return this.hasTag('Noun');
}
public get isVerb(): boolean {
return this.hasTag('Verb');
}
public get isAdverb(): boolean {
return this.hasTag('Adverb');
}
public get isAdjective(): boolean {
return this.hasTag('Adjective');
}
public hasTag(tagName: string): boolean {
// tslint:disable-next-line:no-string-literal
return this.tags[tagName];
}
public addTag(tagName: string): Word {
this.tags[tagName] = true;
return this;
}
public removeTag(tagName: string): Word {
delete this.tags[tagName];
return this;
}
public addChild(word: Word): Word {
this.children.push(word);
return this;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment