WordDatabase.ts 756 Bytes
import { assert } from "console";
const Database = require("better-sqlite3");

export class WordDatabase {
  private words: string[] = [];
  constructor(db_path: string) {
    const db = new Database("./database.db", {
      readonly: true,
    });
    db.prepare(`SELECT * FROM words`)
      .all()
      .forEach((w: any) => {
        this.words.push(w["word"]);
      });
    if (this.words.length < 3) {
      throw new Error("Not enough words.");
    }
  }

  public getWords(count: number): string[] {
    let words: string[] = [];
    let temp = this.words.slice();
    for (let i = 0; i < count; i++) {
      const idx = Math.floor(Math.random() * temp.length);
      words.push(temp[idx]);
      temp.splice(idx, 1);
    }
    return words;
  }
}