UNPKG

nhb-anagram-generator

Version:

A JavaScript/TypeScript library to generate meaningful anagrams.

42 lines (41 loc) 1.73 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.generateAnagrams = generateAnagrams; const english_words_json_1 = __importDefault(require("./data/english-words.json")); const dictionary = new Set(english_words_json_1.default.words); /** * * Utility to generate unique anagrams of a word. * * By default returns maximum of `100` `valid (available in dictionary) anagrams`. * @param word The word for generating anagrams. * @param options The options to generate anagrams: limit the output, whether to lookup in the dictionary. * @returns An array of generated anagrams `(in lowercase)`. The first element is always the given word. */ function generateAnagrams(word, options) { if (word.length <= 1) return [word]; const { limit = 100, validWords = true } = options || {}; const uniqueAnagrams = new Set(); /** * * Helper function to generate permutations. * @param str Current permutation being formed. * @param remaining Remaining characters to process. */ const _permute = (str, remaining) => { if (!remaining.length) { if (!validWords || dictionary.has(str)) { uniqueAnagrams.add(str); } return; } for (let i = 0; i < remaining.length; i++) { if (limit !== 'all' && uniqueAnagrams.size >= limit) return; _permute(str + remaining[i], remaining.slice(0, i) + remaining.slice(i + 1)); } }; _permute('', word.toLowerCase()); return Array.from(uniqueAnagrams); }