aboutsummaryrefslogtreecommitdiff
path: root/api/sentence.ts
blob: 1d22be367301fa46eb9c3dbdfcca26a61fde10c2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import { SearchSentenceResult } from "../search/types.ts";
import APIBase from "./base.ts";
import { JapaneseFormatter } from "./japanese.ts";
import Word from "./word.ts";

export default class Sentence extends APIBase {
  public words: Array<Word> = [];
	protected query?: SearchSentenceResult;
	protected original: string = "";

	public ready: Promise<void>;
	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"].search.sentence(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!.words[token]).withParent(await this.api));

			i += this.query!.words[token].source.length;
			if (i == this.original.length) break;
			token++;

			// continue if there are no unrecognized gaps between words
			if (this.query!.words[token]?.start == i) continue;
			var remainder = this.original.substring(i, this.query!.words[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);
		}, "");
	}
}