Skip to content

Instantly share code, notes, and snippets.

@IntegerMan
Last active Feb 20, 2020
Embed
What would you like to do?
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