UNPKG

@palasimi/ipa-cluster

Version:

Cluster words with similar IPA transcriptions together

91 lines 2.73 kB
"use strict"; // SPDX-License-Identifier: GPL-3.0-or-later // Copyright (c) 2023 Levi Gruspe // Tries. Object.defineProperty(exports, "__esModule", { value: true }); exports.Trie = void 0; /** * A node in a trie. */ class TrieNode { constructor() { // Maps transition symbols to children nodes. this.children = new Map(); // Languages for which the node is an accept state. this.acceptedLanguages = new Set(); } /** * Checks if the state is an accept state for the given language. * If `language` is "_", returns true if the state is an accept state for any * language. */ accepts(language = "_") { const languages = this.acceptedLanguages; if (language === "_") { return languages.size > 0; } return languages.has("_") || languages.has(language); } } /** * A trie used for string matching. */ class Trie { constructor() { this.root = new TrieNode(); } /** * Adds a sequence to the trie. * "_"s are ignored. * * @param input - Input string to use as transition symbols * @param language - Language for which the target state of the input is an * accept state ("_" stands for don't care) */ add(input, language = "_") { let node = this.root; for (const symbol of input) { // Ignore "_". // Normal tries don't do this. if (symbol === "_") { continue; } let child = node.children.get(symbol); if (child == null) { child = new TrieNode(); node.children.set(symbol, child); } node = child; } // Set accept state. node.acceptedLanguages.add(language); } /** * Checks if the input string brings the trie to an accept state at some * point for the given language. * Returns true as soon as an accept state is reached. */ test(input, language = "_") { let node = this.root; // Early return if already at an accept state. // Normal tries don't do this. if (node.accepts(language)) { return true; } for (const symbol of input) { const child = node.children.get(symbol); if (child == null) { return false; } node = child; // Early return if already at an accept state. // Normal tries don't do this. if (node.accepts(language)) { return true; } } return node.accepts(language); } } exports.Trie = Trie; //# sourceMappingURL=trie.js.map