### Get All Keywords and Metadata (JavaScript) Source: https://context7.com/tonyzhou1890/js-mdict/llms.txt Shows how to retrieve a list of all keywords along with their metadata, specifically the `recordStartOffset`, using the `rangeKeyWords` method. This is useful for building custom indexes or performing operations on the entire dictionary's keyword set. An example demonstrates creating an index organized by the first letter of each word. ```javascript const Mdict = require('mdict-js'); const dict = new Mdict('path/to/dictionary.mdx'); // Get all keywords with record information const allKeywords = dict.rangeKeyWords(); console.log(allKeywords); /* [ { keyText: 'aardvark', recordStartOffset: 1024 }, { keyText: 'abandon', recordStartOffset: 2048 }, ... ] */ // Build custom index const customIndex = {}; allKeywords.forEach(item => { const firstLetter = item.keyText[0].toUpperCase(); if (!customIndex[firstLetter]) { customIndex[firstLetter] = []; } customIndex[firstLetter].push(item); }); console.log(`Words starting with 'A': ${customIndex['A'].length}`); ``` -------------------------------- ### Load and Search MDX Dictionary in JavaScript Source: https://github.com/tonyzhou1890/js-mdict/blob/master/js-mdict-README.md Demonstrates how to load an MDX dictionary file using the Mdict class and perform various search operations. This includes looking up definitions, finding words with a given prefix, and getting word suggestions. Note that MDD files only support the lookup method. ```javascript import Mdict from 'js-mdict'; // Note: *.mdd file only support lookup method. // loading dictionary const dict = new Mdict('mdx/testdict/oale8.mdx'); // console.log(mdict.lookup('interactive')); // console.log(mdict.bsearch('interactive')); // console.log(mdict.fuzzy_search('interactive', 5)); // console.log(mdict.prefix('interactive')); console.log(dict.lookup('hello')); /* { keyText: "hello", definition: "你好", } */ console.log(dict.prefix('hello')); /* [ { key: 'he', rofset: 64744840 }, { key: 'hell', rofset: 65513175 }, { key: 'hello', rofset: 65552694 } ] */ let word = 'informations'; dict.suggest(word).then((sw) => { // eslint-disable-next-line console.log(sw); /* [ 'information', "information's" ] */ }); word = 'hitch'; const fws = dict.fuzzy_search(word, 20, 5); console.log(fws); /* [ { key: 'history', rofset: 66627131, ed: 4 }, { key: 'hit', rofset: 66648124, ed: 2 }, { key: 'hit back', rofset: 66697464, ed: 4 }, { key: 'hit back', rofset: 66697464, ed: 4 }, { key: 'hit big', rofset: 66698789, ed: 4 }, { key: 'hitch', rofset: 66698812, ed: 0 }, { key: 'hitched', rofset: 66706586, ed: 2 }, { key: 'hitcher', rofset: 66706602, ed: 2 }, { key: 'hitches', rofset: 66706623, ed: 2 }, { key: 'hitchhike', rofset: 66706639, ed: 4 }, { key: 'hitchhiker', rofset: 66710697, ed: 5 }, { key: 'hitching', rofset: 66712273, ed: 3 }, { key: 'hi-tech', rofset: 66712289, ed: 2 }, { key: 'hit for', rofset: 66713795, ed: 4 } ] */ console.log(dict.parse_defination(fws[0].key, fws[0].rofset)); /* { keyText: 'history', definition: ' { const definition = dict.lookup(item.key); console.log(`${item.key}: ${definition.definition.substring(0, 50)}...`); }); ``` -------------------------------- ### JavaScript Associate Search with mdict-js Source: https://context7.com/tonyzhou1890/js-mdict/llms.txt Retrieves words that start with a given phrase, potentially searching across multiple key blocks. This is useful for building autocomplete suggestions. The results contain the key text and record offsets. ```javascript const Mdict = require('mdict-js'); const dict = new Mdict('path/to/dictionary.mdx'); // Find associated words const associated = dict.associate('inter'); console.log(associated); /* [ { keyText: 'inter', recordStartOffset: 23456789, rofset: 23456789 }, { keyText: 'interact', recordStartOffset: 23457890, rofset: 23457890 }, { keyText: 'interaction', recordStartOffset: 23458901, rofset: 23458901 }, { keyText: 'interactive', recordStartOffset: 23459012, rofset: 23459012 }, { keyText: 'intercept', recordStartOffset: 23460123, rofset: 23460123 }, { keyText: 'interest', recordStartOffset: 23461234, rofset: 23461234 }, { keyText: 'international', recordStartOffset: 23462345, rofset: 23462345 } ] */ // Build autocomplete suggestions const userInput = 'progr'; const suggestions = dict.associate(userInput) .slice(0, 10) // Limit to 10 suggestions .map(item => item.keyText); console.log(suggestions); /* ['program', 'programme', 'programmer', 'programming', 'progress', 'progressive', ...] */ ``` -------------------------------- ### Get All Dictionary Keys Source: https://context7.com/tonyzhou1890/js-mdict/llms.txt Retrieves all words (keys) available in the dictionary. This method is only applicable to MDX files. Keys are cached in memory for MDX files from version 10 onwards, ensuring fast retrieval. ```APIDOC ## Get All Dictionary Keys ### Description Retrieves all words (keys) available in the dictionary. This method is only applicable to MDX files (not MDD files). Keys are cached in memory for MDX files from version 10 onwards, ensuring fast retrieval. ### Method `dict.keys()` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript const Mdict = require('mdict-js'); const dict = new Mdict('path/to/dictionary.mdx'); // Get all keys const allWords = dict.keys(); console.log(allWords); // Expected output: // [ // 'aardvark', // 'abandon', // 'hello', // 'world', // 'zebra', // ... // ] // Count total entries console.log(`Dictionary contains ${allWords.length} entries`); // Filter words by criteria const wordsStartingWithA = allWords.filter(word => word.startsWith('a')); console.log(`Found ${wordsStartingWithA.length} words starting with 'a'`); // Build a letter index const letterIndex = {}; allWords.forEach(word => { const firstLetter = word[0].toUpperCase(); letterIndex[firstLetter] = (letterIndex[firstLetter] || 0) + 1; }); console.log('Words per letter:', letterIndex); ``` ### Response #### Success Response (200) - **allWords** (Array) - An array containing all the words (keys) in the dictionary. #### Response Example ```json [ "aardvark", "abandon", "hello", "world", "zebra" ] ``` ``` -------------------------------- ### Work with MDD Media Files (JavaScript) Source: https://context7.com/tonyzhou1890/js-mdict/llms.txt Details how to access multimedia resources (images, audio, CSS) stored in MDD files. The `lookup` method is used on an MDict instance loaded with an MDD file, returning base64-encoded data. The example shows how to decode this data into a buffer for saving files or embedding directly into HTML. ```javascript const Mdict = require('mdict-js'); // Load MDD file for multimedia resources const mdd = new Mdict('path/to/dictionary.mdd'); // Lookup returns base64-encoded data for MDD files const imageData = mdd.lookup('images/example.png'); if (imageData.definition) { // definition contains base64-encoded binary data const base64Data = imageData.definition; // In Node.js, convert to Buffer and save const buffer = Buffer.from(base64Data, 'base64'); require('fs').writeFileSync('example.png', buffer); // Or use directly in HTML const imgTag = ``; } // Lookup audio file const audioData = mdd.lookup('sound/pronunciation.mp3'); if (audioData.definition) { const audioBuffer = Buffer.from(audioData.definition, 'base64'); require('fs').writeFileSync('pronunciation.mp3', audioBuffer); } // Note: Only lookup() method is supported for MDD files // prefix, associate, fuzzy_search are NOT available for MDD ``` -------------------------------- ### JavaScript Spell Checking and Suggestions with mdict-js Source: https://context7.com/tonyzhou1890/js-mdict/llms.txt Provides functionality to get spelling suggestions for a given word using an English dictionary and the nspell library. This is an asynchronous operation returning a Promise. It can be used to check spelling and find the most likely correct word. ```javascript const Mdict = require('mdict-js'); const dict = new Mdict('path/to/dictionary.mdx'); // Get spelling suggestions (returns Promise) async function checkSpelling(word) { try { const suggestions = await dict.suggest('informations'); console.log(suggestions); /* [ 'information', "information's" ] */ return suggestions; } catch (error) { console.error('Spell check failed:', error); return []; } } // Use in async context dict.suggest('definately') .then(suggestions => { console.log('Suggestions:', suggestions); // ['definitely', 'defiantly', 'define'] }) .catch(err => console.error(err)); // Combined spell check and lookup async function smartLookup(word, dict) { let result = dict.lookup(word); if (!result.definition) { console.log(`"${word}" not found, checking spelling...`); const suggestions = await dict.suggest(word); if (suggestions.length > 0) { console.log(`Did you mean: ${suggestions.join(', ')}?`); result = dict.lookup(suggestions[0]); } } return result; } ``` -------------------------------- ### Get All Dictionary Keys in JavaScript Source: https://context7.com/tonyzhou1890/js-mdict/llms.txt Retrieves all available words (keys) from an MDX dictionary file. This operation is very fast due to in-memory caching of keys introduced in version 10. It can be used to count entries, filter words based on criteria, or build auxiliary data structures like letter indexes. ```javascript const Mdict = require('mdict-js'); const dict = new Mdict('path/to/dictionary.mdx'); // Get all keys const allWords = dict.keys(); console.log(allWords); /* [ 'aardvark', 'abandon', 'hello', 'world', 'zebra', ... ] */ // Count total entries console.log(`Dictionary contains ${allWords.length} entries`); // Filter words by criteria const wordsStartingWithA = allWords.filter(word => word.startsWith('a')); console.log(`Found ${wordsStartingWithA.length} words starting with 'a'`); // Build a letter index const letterIndex = {}; allWords.forEach(word => { const firstLetter = word[0].toUpperCase(); letterIndex[firstLetter] = (letterIndex[firstLetter] || 0) + 1; }); console.log('Words per letter:', letterIndex); ``` -------------------------------- ### Basic Dictionary Initialization Source: https://context7.com/tonyzhou1890/js-mdict/llms.txt Initializes an MDict dictionary by providing the path to an mdx or mdd file. Optional configuration parameters can control key matching behavior, and a passcode can be provided for encrypted dictionaries. ```APIDOC ## Basic Dictionary Initialization ### Description Initializes an MDict dictionary by providing the path to an mdx or mdd file. Optional configuration parameters can control key matching behavior, and a passcode can be provided for encrypted dictionaries. ### Method `new Mdict(filePath, options)` ### Parameters #### Path Parameters - **filePath** (string) - Required - The path to the MDict dictionary file (.mdx or .mdd). #### Query Parameters None #### Request Body None ### Options (Optional Object) - **passcode** (string) - Optional - Decryption password for encrypted dictionaries. - **keyCaseSensitive** (boolean) - Optional - Set to `true` for case-sensitive key matching. Defaults to `false`. - **stripKey** (boolean) - Optional - Set to `true` to strip special characters from keys. Defaults to `false`. ### Request Example ```javascript const Mdict = require('mdict-js'); // Basic initialization const dict = new Mdict('path/to/dictionary.mdx'); // With options const dictWithOptions = new Mdict('path/to/dictionary.mdx', { passcode: 'encryption_key', keyCaseSensitive: false, stripKey: true }); // For encrypted dictionary files const encryptedDict = new Mdict('path/to/encrypted.mdx', { passcode: 'mySecretPassword' }); ``` ### Response - **dict** (Mdict instance) - An instance of the Mdict class representing the initialized dictionary. ``` -------------------------------- ### Initialize MDict Dictionary in JavaScript Source: https://context7.com/tonyzhou1890/js-mdict/llms.txt Initializes an mdict-js dictionary instance. It accepts the path to an MDX or MDD file and optional configuration parameters for handling encrypted files, case sensitivity in key matching, and stripping special characters from keys. ```javascript const Mdict = require('mdict-js'); // Basic initialization const dict = new Mdict('path/to/dictionary.mdx'); // With options const dictWithOptions = new Mdict('path/to/dictionary.mdx', { passcode: 'encryption_key', // Optional: decryption password for encrypted dictionaries keyCaseSensitive: false, // Optional: case-sensitive key matching stripKey: true // Optional: strip special characters from keys }); // For encrypted dictionary files const encryptedDict = new Mdict('path/to/encrypted.mdx', { passcode: 'mySecretPassword' }); ``` -------------------------------- ### js-mdict v3.x API Usage Source: https://github.com/tonyzhou1890/js-mdict/blob/master/js-mdict-README.md Demonstrates the API for js-mdict version 3.x, including lookup, prefix search, fuzzy search, and parsing definitions. This version loads the entire dictionary data to build the index, which can be time-consuming. ```javascript import Mdict from 'js-mdict'; const mdict = new Mdict('mdx/oale8.mdx'); console.log(mdict.lookup('hello')); console.log(mdict.prefix('hello')); // get fuzzy words fuzzy_words = mdict.fuzzy_search( 'wrapper', 5, /* fuzzy words size */ 5 /* edit_distance */ ); /* example output: [ { ed: 0, idx: 108605, key: 'wrapper' }, { ed: 1, idx: 108603, key: 'wrapped' }, { ed: 1, idx: 108606, key: 'wrappers' }, { ed: 3, idx: 108593, key: 'wrapper' }, { ed: 3, idx: 108598, key: 'wrap' }, { ed: 3, idx: 108607, key: 'wrapping' }, { ed: 4, idx: 108594, key: 'wranglers' }, { ed: 4, idx: 108595, key: 'wrangles' }, { ed: 4, idx: 108609, key: 'wrappings' } ] */ // get definition console.log(mdict.parse_defination(fuzzy_words[0].idx)); ``` -------------------------------- ### Mixed Mode Lookup in mdict-js (JavaScript) Source: https://github.com/tonyzhou1890/js-mdict/blob/master/README.md Demonstrates how to use the 'mixed' mode in mdict-js for case-insensitive lookups and retrieving all matched words. This mode requires the 'mdict-js' package and takes longer to initialize. It returns an array of matching entries, each with a 'keyText' and 'definition'. ```javascript const Mdict = require('mdict-js') const dict = new Mdict('path/xxx.mdx', { mode: 'mixed' }) const res = dict.lookup('be') console.log(res) /** [ { keyText: 'be', definition: 'xxx' }, { keyText: 'Be', definition: 'xxx' }, { keyText: 'be-', definition: 'xxx' } ] **/ ``` -------------------------------- ### Parse Definition by Offset (JavaScript) Source: https://context7.com/tonyzhou1890/js-mdict/llms.txt Explains how to retrieve a word's definition using its record offset, particularly useful when dealing with results from fuzzy searches. The `parse_defination` method takes the keyword and its offset to fetch the precise definition content, which can include HTML markup. This snippet also shows batch processing and integration with `associate` results. ```javascript const Mdict = require('mdict-js'); const dict = new Mdict('path/to/dictionary.mdx'); // Get fuzzy search results const fuzzyWords = dict.fuzzy_search('hitch', 20, 5); // Parse definition using offset from fuzzy search const definition = dict.parse_defination(fuzzyWords[0].key, fuzzyWords[0].rofset); console.log(definition); /* { keyText: 'hitch', definition: '...Definition of hitch...' } */ // Batch process fuzzy search results fuzzyWords.forEach(item => { const def = dict.parse_defination(item.key, item.rofset); console.log(`${item.key} (edit distance: ${item.ed})`); console.log(def.definition.substring(0, 100) + '...\n'); }); // Use with associate results const associated = dict.associate('test'); associated.forEach(item => { const def = dict.parse_defination(item.keyText, item.rofset); console.log(`${item.keyText}: ${def.definition}`); }); ``` -------------------------------- ### Lemmatize Words for Dictionary Matching (JavaScript) Source: https://context7.com/tonyzhou1890/js-mdict/llms.txt Demonstrates how to obtain the base (lemma) form of a word using the `lemmer` method. This is crucial for improving dictionary lookups by matching inflected words to their root forms. The `lemmaLookup` function shows a practical application by first attempting an exact match and then falling back to the lemmatized form. ```javascript const Mdict = require('mdict-js'); const dict = new Mdict('path/to/dictionary.mdx'); // Get lemma of inflected words const lemma1 = dict.lemmer('running'); console.log(lemma1); // 'run' const lemma2 = dict.lemmer('computers'); console.log(lemma2); // 'computer' const lemma3 = dict.lemmer('better'); console.log(lemma3); // 'good' // Use for improved lookups function lemmaLookup(word, dict) { // Try exact match first let result = dict.lookup(word); if (result.definition) return result; // Try lemmatized form const lemma = dict.lemmer(word); if (lemma !== word) { result = dict.lookup(lemma); if (result.definition) { console.log(`Showing definition for "${lemma}" (lemma of "${word}")`); return result; } } return { keyText: word, definition: null }; } // Example usage const runningDef = lemmaLookup('running', dict); const computersDef = lemmaLookup('computers', dict); ``` -------------------------------- ### js-mdict v2.0.3 API Usage Source: https://github.com/tonyzhou1890/js-mdict/blob/master/js-mdict-README.md Illustrates the API for js-mdict version 2.0.3, focusing on building the dictionary and performing lookups. Note that this version does not support MDD files or encrypted record info files. ```javascript import path from 'path'; import Mdict from 'js-mdict'; const dictPath = path.join(__dirname, '../resource/Collins.mdx'); const mdict = new Mdict(dictPath); mdict .build() .then((_mdict) => { console.log('hello', _mdict.lookup('hello')); console.log('world', _mdict.lookup('world')); console.log(_mdict.attr()); }) .catch((err) => { console.error(err); }); ``` -------------------------------- ### Lookup Word Definition in JavaScript Source: https://context7.com/tonyzhou1890/js-mdict/llms.txt Performs a lookup for a given word in the MDict dictionary and returns its definition. If the word is not found, it returns an object with a null definition. Case-insensitive lookup is the default behavior. ```javascript const Mdict = require('mdict-js'); const dict = new Mdict('path/to/dictionary.mdx'); // Simple lookup const result = dict.lookup('hello'); console.log(result); /* { keyText: 'hello', definition: 'Definition of hello: a greeting...' } */ // Word not found const notFound = dict.lookup('nonexistentword'); console.log(notFound); /* { keyText: 'nonexistentword', definition: null } */ // Case-insensitive lookup (default behavior) const hello1 = dict.lookup('Hello'); const hello2 = dict.lookup('HELLO'); // Both return the same definition ``` -------------------------------- ### Word Lookup Source: https://context7.com/tonyzhou1890/js-mdict/llms.txt Looks up a word in the dictionary and retrieves its definition. Returns an object containing the word and its definition, or null if the word is not found. ```APIDOC ## Word Lookup ### Description Looks up a word in the dictionary and retrieves its definition. Returns an object containing the word and its definition, or null if the word is not found. The lookup is case-insensitive by default. ### Method `dict.lookup(word)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **word** (string) - Required - The word to look up in the dictionary. ### Request Example ```javascript const Mdict = require('mdict-js'); const dict = new Mdict('path/to/dictionary.mdx'); // Simple lookup const result = dict.lookup('hello'); console.log(result); // Expected output: // { // keyText: 'hello', // definition: 'Definition of hello: a greeting...' // } // Word not found const notFound = dict.lookup('nonexistentword'); console.log(notFound); // Expected output: // { // keyText: 'nonexistentword', // definition: null // } ``` ### Response #### Success Response (200) - **keyText** (string) - The word that was looked up. - **definition** (string | null) - The HTML definition of the word, or `null` if the word was not found. #### Response Example ```json { "keyText": "hello", "definition": "Definition of hello: a greeting..." } ``` ``` -------------------------------- ### JavaScript Fuzzy Search with mdict-js Source: https://context7.com/tonyzhou1890/js-mdict/llms.txt Performs fuzzy searches to find similar words based on Levenshtein edit distance. This is useful for spell checking and approximate matching. The function takes the search term, a maximum edit distance, and a maximum number of results. ```javascript const Mdict = require('mdict-js'); const dict = new Mdict('path/to/dictionary.mdx'); // Fuzzy search with edit distance const fuzzyResults = dict.fuzzy_search('hitch', 20, 5); console.log(fuzzyResults); /* [ { key: 'hitch', rofset: 66698812, ed: 0 }, // exact match { key: 'hit', rofset: 66648124, ed: 2 }, // edit distance 2 { key: 'hitched', rofset: 66706586, ed: 2 }, { key: 'hitcher', rofset: 66706602, ed: 2 }, { key: 'hitches', rofset: 66706623, ed: 2 }, { key: 'history', rofset: 66627131, ed: 4 }, { key: 'hit back', rofset: 66697464, ed: 4 }, { key: 'hitchhike', rofset: 66706639, ed: 4 } ] */ // Find spelling corrections const misspelled = 'recieve'; const corrections = dict.fuzzy_search(misspelled, 10, 2) .filter(item => item.ed > 0) // Exclude exact match .sort((a, b) => a.ed - b.ed) // Sort by edit distance .slice(0, 5); // Top 5 suggestions console.log('Did you mean:', corrections.map(c => c.key)); /* Did you mean: [ 'receive', 'receiver', 'received', 'receives', 'receiving' ] */ // Tolerant search for user typos function tolerantSearch(word, dict) { const exact = dict.lookup(word); if (exact.definition) return exact; const fuzzy = dict.fuzzy_search(word, 5, 3); if (fuzzy.length > 0) { return dict.lookup(fuzzy[0].key); } return null; } ``` -------------------------------- ### Check Word Existence Source: https://context7.com/tonyzhou1890/js-mdict/llms.txt Checks if a word exists in the dictionary without retrieving its full definition. This method is optimized for performance and only checks for the presence of the word. ```APIDOC ## Check Word Existence ### Description Checks if a word exists in the dictionary without retrieving its full definition. This method is optimized for performance and only checks for the presence of the word. ### Method `dict.isExist(word)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **word** (string) - Required - The word to check for existence in the dictionary. ### Request Example ```javascript const Mdict = require('mdict-js'); const dict = new Mdict('path/to/dictionary.mdx'); // Check if words exist const exists1 = dict.isExist('hello'); console.log(exists1); // true const exists2 = dict.isExist('nonexistentword'); console.log(exists2); // false // Useful for validation before lookup if (dict.isExist('computer')) { const definition = dict.lookup('computer'); console.log(definition.definition); } // Batch validation const wordsToCheck = ['hello', 'world', 'foo', 'bar']; const existingWords = wordsToCheck.filter(word => dict.isExist(word)); console.log('Found words:', existingWords); // ['hello', 'world'] ``` ### Response #### Success Response (200) - **exists** (boolean) - `true` if the word exists in the dictionary, `false` otherwise. #### Response Example ```json true ``` ``` -------------------------------- ### Check Word Existence in JavaScript Source: https://context7.com/tonyzhou1890/js-mdict/llms.txt Efficiently checks if a word exists in the dictionary without retrieving its full definition. This method is optimized for performance by only verifying presence. It is useful for input validation before performing a full lookup and can be used for batch checking. ```javascript const Mdict = require('mdict-js'); const dict = new Mdict('path/to/dictionary.mdx'); // Check if words exist const exists1 = dict.isExist('hello'); console.log(exists1); // true const exists2 = dict.isExist('nonexistentword'); console.log(exists2); // false // Useful for validation before lookup if (dict.isExist('computer')) { const definition = dict.lookup('computer'); console.log(definition.definition); } // Batch validation const wordsToCheck = ['hello', 'world', 'foo', 'bar']; const existingWords = wordsToCheck.filter(word => dict.isExist(word)); console.log('Found words:', existingWords); // ['hello', 'world'] ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.