demo.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. "use strict";
  2. // Type letters to see matches narrow; backspace to undo; Ctrl+C to quit.
  3. // Usage: node demo.js
  4. const fs = require("fs");
  5. const path = require("path");
  6. const { Predictor } = require("./predictor");
  7. const { words } = JSON.parse(
  8. fs.readFileSync(path.join(__dirname, "wordlist.json"), "utf8")
  9. );
  10. const predictor = new Predictor(words);
  11. let prefix = "";
  12. function render() {
  13. const { matches, isWord, completion } = predictor.predict(prefix);
  14. console.clear();
  15. console.log(`typed: ${prefix || "(nothing yet)"}`);
  16. if (completion) {
  17. console.log(`-> unique match: ${completion}`);
  18. } else if (matches.length === 0) {
  19. console.log("-> no matches");
  20. } else {
  21. const shown = matches.slice(0, 15);
  22. console.log(
  23. `-> ${matches.length} matches: ${shown.join(", ")}` +
  24. (matches.length > shown.length ? ", ..." : "")
  25. );
  26. }
  27. if (isWord && matches.length > 1) {
  28. console.log(` (note: "${prefix}" is itself a word, but is also a prefix of others)`);
  29. }
  30. }
  31. process.stdin.setRawMode(true);
  32. process.stdin.resume();
  33. process.stdin.setEncoding("utf8");
  34. render();
  35. process.stdin.on("data", (key) => {
  36. if (key === "\u0003") process.exit(0); // Ctrl+C
  37. if (key === "\u007f" || key === "\b") {
  38. prefix = prefix.slice(0, -1);
  39. } else if (/^[a-z]$/i.test(key)) {
  40. prefix += key.toLowerCase();
  41. }
  42. render();
  43. });