aboutsummaryrefslogtreecommitdiff
path: root/api/word.ts
blob: 4dad4a31cff4fcb4ea887063adc091ccce0957f0 (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
import Glossary from "./glossary.ts";
import APIBase from "./base.ts";
import Japanese, { JapaneseFormatter } from "./japanese.ts";

import "../util/string.ts";
import { TagGroup } from "../search/tags.ts";
import { SearchWord } from "../search/types.ts";

export default class Word extends APIBase {
	/** @prop dictionary form of verb if this word is a verb */
	protected base: Japanese;
	/** @prop word as written in parent sentence */
	protected text: Japanese;
	/** @prop this.furigana should output kanji with reading */
	protected outputKanji: boolean = true;
	/** @prop this word represents an unrecognized sentence part between recognized terms */
	protected filler: boolean;

  constructor(input: string | SearchWord) {
		super();
		if (typeof input === "string") {
			this.filler = true;
			input = input as string;
			this.base = new Japanese(input, input);
			this.text = this.base;
			this.outputKanji = false;
		} else {
			this.filler = false;
			input = input as SearchWord;
			this.base = new Japanese(input.writing, input.reading);
			if (input.tags.anyOf(TagGroup.Conjugable as string[])) {
				var writingCommon = input.writing.cmpLen(input.source);
				var readingCommon = input.reading.cmpLen(input.source);
				var stemLength = Math.max(writingCommon, readingCommon);
				var base = input[writingCommon > readingCommon ? "writing" : "reading"].substring(stemLength);
				var conjugation = input.source.substring(stemLength);
				this.text = new Japanese(input.writing.replaceLast(base, conjugation),
																 input.reading.replaceLast(base, conjugation));
			} else {
				this.text = this.base;
			}
			this.outputKanji = input.source.hasKanji(); // only output kanji if input also uses kanji
		}
  }

	furigana(format: JapaneseFormatter) {
		if (!this.outputKanji) return this.text.reading;
		else return this.text.furigana(format);
	}

  async glossary() {
		// TODO: output nothing if this.filler == true
    return new Glossary().withParent(await this.api);
  }
}