import { ParseResult } from "../language/types.ts"; import APIBase from "./base.ts"; import Japanese, { JapaneseFormatter } from "./japanese.ts"; import Word from "./word.ts"; export default class Sentence extends APIBase { public words: Array = []; protected query?: ParseResult; protected original: string = ""; public ready: Promise; private _resolveReady: () => void = () => {}; constructor(input: string) { super(); this.ready = new Promise(res => this._resolveReady = res); this.fetch(input); } first(searchValue: RegExp | string): Word | undefined { return this.words[0]; } private async fetch(input: string) { this.original = input; this.query = await (await this.api)["core"].parseSentence(input); await this.updateWords(); this._resolveReady(); } private async updateWords() { this.words.clear(); let token = 0; let i = 0; while (i < this.original.length) { this.words.push(new Word(this.query!.tokens[token]).withParent(await this.api)); i += this.query!.tokens[token].source.length; if (i == this.original.length) break; token++; // continue if there are no unrecognized gaps between tokens if (this.query!.tokens[token]?.start == i) continue; var remainder = this.original.substring(i, this.query!.tokens[token]?.start); this.words.push(new Word(remainder).withParent(await this.api)); i += remainder.length; } } furigana(format: JapaneseFormatter = "HTML"): string { return this.words.reduce((out, word) => { return out + word.furigana(format); }, ""); } }