@mahmoud_magdy_mahmoud/smart-word-generator 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,118 @@
1
+ <p align="center">
2
+ <!-- <img src="./logo.png"> -->
3
+ <!-- Logo generation is temporarily unavailable. Place your logo here. -->
4
+ </p>
5
+ <h1 align="center">Smart Word Generator</h1>
6
+ <p align="center"><b>A TypeScript library for generating words using artificial intelligence depending on your needs.</b></p>
7
+
8
+ ## Description
9
+
10
+ Smart word generator is a library for generating words using artificial intelligence via the [Datamuse API](https://www.datamuse.com/api/). It allows you to find words with similar meanings, sounds, spellings, and various other relationships.
11
+
12
+ Now fully rewritten in **TypeScript** for better developer experience and type safety!
13
+
14
+ ## Features
15
+
16
+ * **Type-Safe**: Written in TypeScript with full type definitions.
17
+ * **Unified API**: All functions accept a consistent options object.
18
+ * **Rich Relationships**: Generate synonyms, antonyms, rhymes, and more.
19
+ * **Flexible Filtering**: distinct parts of speech, topics, and patterns.
20
+
21
+ ## Installation
22
+
23
+ ```bash
24
+ npm install smart-word-generator
25
+ ```
26
+
27
+ ## Usage
28
+
29
+ Import the functions you need from the package:
30
+
31
+ ```typescript
32
+ import {
33
+ generateWordMeansLike,
34
+ generateRhyme,
35
+ generateSynonym,
36
+ generateAntonym,
37
+ generateWordSoundsLike
38
+ } from "smart-word-generator";
39
+ ```
40
+
41
+ ### Options Object
42
+
43
+ All generator functions accept an optional `options` object:
44
+
45
+ ```typescript
46
+ interface GeneratorOptions {
47
+ transformToArray?: boolean; // Return string[] if true, else detailed object[]
48
+ partOfSpeech?: 'n' | 'v' | 'adj' | 'adv';
49
+ topics?: string; // Context topics
50
+ startWith?: string; // Filter words starting with...
51
+ endWith?: string; // Filter words ending with...
52
+ max?: number; // Max results
53
+ }
54
+ ```
55
+
56
+ ### Examples
57
+
58
+ #### Find words with similar meaning
59
+ ```typescript
60
+ const words = await generateWordMeansLike("great", {
61
+ partOfSpeech: "adj",
62
+ transformToArray: true,
63
+ max: 5
64
+ });
65
+ console.log(words);
66
+ // Output: ['big', 'huge', 'vast', 'large', 'grand']
67
+ ```
68
+
69
+ #### Find Rhymes
70
+ ```typescript
71
+ const rhymes = await generateRhyme("cat", { max: 5, transformToArray: true });
72
+ console.log(rhymes);
73
+ // Output: ['hat', 'bat', 'rat', 'mat', 'fat']
74
+ ```
75
+
76
+ #### Find Synonyms
77
+ ```typescript
78
+ await generateSynonym("happy");
79
+ ```
80
+
81
+ #### Find Antonyms
82
+ ```typescript
83
+ await generateAntonym("hot");
84
+ ```
85
+
86
+ #### Find Words Sounding Like
87
+ ```typescript
88
+ await generateWordSoundsLike("flower");
89
+ ```
90
+
91
+ #### Find Adjectives describing a Noun
92
+ ```typescript
93
+ // Find adjectives often used to describe 'ocean'
94
+ await generateAdjectiveForNoun("ocean");
95
+ ```
96
+
97
+ #### Find Nouns described by an Adjective
98
+ ```typescript
99
+ // Find nouns often described as 'blue'
100
+ await generateNounForAdjective("blue");
101
+ ```
102
+
103
+ ## API List
104
+
105
+ * `generateWordMeansLike(word, options)`
106
+ * `generateWordSoundsLike(word, options)`
107
+ * `generateWordSpelledLike(word, options)`
108
+ * `generateRhyme(word, options)`
109
+ * `generateSynonym(word, options)`
110
+ * `generateAntonym(word, options)`
111
+ * `generateAdjectiveForNoun(word, options)`
112
+ * `generateNounForAdjective(word, options)`
113
+ * `generateWordHasLeftContext(word, options)`
114
+ * `generateWordHasRightContext(word, options)`
115
+ * `generateRelatedWord(word, relationCode, options)`
116
+
117
+ ## License
118
+ ISC
@@ -0,0 +1,48 @@
1
+ import { GeneratorOptions, DatamuseWord } from "../utils";
2
+ /**
3
+ * Generate words that have similar meaning to the input word.
4
+ */
5
+ export declare const generateWordMeansLike: (word: string, options?: GeneratorOptions) => Promise<string[] | DatamuseWord[]>;
6
+ /**
7
+ * Generate words that sound like the input word.
8
+ */
9
+ export declare const generateWordSoundsLike: (word: string, options?: GeneratorOptions) => Promise<string[] | DatamuseWord[]>;
10
+ /**
11
+ * Generate words that are spelled like the input word.
12
+ */
13
+ export declare const generateWordSpelledLike: (word: string, options?: GeneratorOptions) => Promise<string[] | DatamuseWord[]>;
14
+ /**
15
+ * Generate words that appear immediately to the left of the target word in a sentence.
16
+ * (Frequent predecessors)
17
+ */
18
+ export declare const generateWordHasLeftContext: (word: string, options?: GeneratorOptions) => Promise<string[] | DatamuseWord[]>;
19
+ /**
20
+ * Generate words that appear immediately to the right of the target word in a sentence.
21
+ * (Frequent followers)
22
+ */
23
+ export declare const generateWordHasRightContext: (word: string, options?: GeneratorOptions) => Promise<string[] | DatamuseWord[]>;
24
+ /**
25
+ * Generate synonyms for the input word.
26
+ */
27
+ export declare const generateSynonym: (word: string, options?: GeneratorOptions) => Promise<string[] | DatamuseWord[]>;
28
+ /**
29
+ * Generate antonyms for the input word.
30
+ */
31
+ export declare const generateAntonym: (word: string, options?: GeneratorOptions) => Promise<string[] | DatamuseWord[]>;
32
+ /**
33
+ * Generate rhymes for the input word.
34
+ */
35
+ export declare const generateRhyme: (word: string, options?: GeneratorOptions) => Promise<string[] | DatamuseWord[]>;
36
+ /**
37
+ * Generate adjectives that are often used to describe the given noun.
38
+ */
39
+ export declare const generateAdjectiveForNoun: (word: string, options?: GeneratorOptions) => Promise<string[] | DatamuseWord[]>;
40
+ /**
41
+ * Generate nouns that are often described by the given adjective.
42
+ */
43
+ export declare const generateNounForAdjective: (word: string, options?: GeneratorOptions) => Promise<string[] | DatamuseWord[]>;
44
+ /**
45
+ * Generate related words using a specific relation code.
46
+ * @param relationCode The Datamuse relation code (e.g., 'rel_trg', 'rel_gen').
47
+ */
48
+ export declare const generateRelatedWord: (word: string, relationCode: string, options?: GeneratorOptions) => Promise<string[] | DatamuseWord[]>;
@@ -0,0 +1,111 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.generateRelatedWord = exports.generateNounForAdjective = exports.generateAdjectiveForNoun = exports.generateRhyme = exports.generateAntonym = exports.generateSynonym = exports.generateWordHasRightContext = exports.generateWordHasLeftContext = exports.generateWordSpelledLike = exports.generateWordSoundsLike = exports.generateWordMeansLike = void 0;
7
+ const axios_1 = __importDefault(require("axios"));
8
+ const utils_1 = require("../utils");
9
+ /**
10
+ * Base function to generate words from Datamuse API.
11
+ * @param queryParam The primary query parameter (e.g., 'ml', 'sl', 'sp', 'rel_syn').
12
+ * @param word The input word.
13
+ * @param options Generator options.
14
+ */
15
+ const generateWords = async (queryParam, word, options = {}) => {
16
+ try {
17
+ const optionalParams = (0, utils_1.wordOptionalParams)(options);
18
+ const url = `https://api.datamuse.com/words?${queryParam}=${encodeURIComponent(word)}&${optionalParams}`;
19
+ // Use generic type for axios response
20
+ const response = await axios_1.default.get(url);
21
+ return (0, utils_1.decorateWords)(response, options);
22
+ }
23
+ catch (err) {
24
+ console.error(`Error generating words for ${queryParam}=${word}:`, err);
25
+ return [];
26
+ }
27
+ };
28
+ /**
29
+ * Generate words that have similar meaning to the input word.
30
+ */
31
+ const generateWordMeansLike = (word, options) => {
32
+ return generateWords("ml", word, options);
33
+ };
34
+ exports.generateWordMeansLike = generateWordMeansLike;
35
+ /**
36
+ * Generate words that sound like the input word.
37
+ */
38
+ const generateWordSoundsLike = (word, options) => {
39
+ return generateWords("sl", word, options);
40
+ };
41
+ exports.generateWordSoundsLike = generateWordSoundsLike;
42
+ /**
43
+ * Generate words that are spelled like the input word.
44
+ */
45
+ const generateWordSpelledLike = (word, options) => {
46
+ return generateWords("sp", word, options);
47
+ };
48
+ exports.generateWordSpelledLike = generateWordSpelledLike;
49
+ /**
50
+ * Generate words that appear immediately to the left of the target word in a sentence.
51
+ * (Frequent predecessors)
52
+ */
53
+ const generateWordHasLeftContext = (word, options) => {
54
+ // 'lc' is the legacy parameter for left context, equivalent to rel_bgb?
55
+ // API docs say 'lc' is "Left Context".
56
+ // We will stick to 'lc' as in original code unless we want to switch to 'rel_bgb'.
57
+ // Let's stick to 'lc' to match exact behavior, but documented as such.
58
+ return generateWords("lc", word, options);
59
+ };
60
+ exports.generateWordHasLeftContext = generateWordHasLeftContext;
61
+ /**
62
+ * Generate words that appear immediately to the right of the target word in a sentence.
63
+ * (Frequent followers)
64
+ */
65
+ const generateWordHasRightContext = (word, options) => {
66
+ return generateWords("rc", word, options);
67
+ };
68
+ exports.generateWordHasRightContext = generateWordHasRightContext;
69
+ /**
70
+ * Generate synonyms for the input word.
71
+ */
72
+ const generateSynonym = (word, options) => {
73
+ return generateWords("rel_syn", word, options);
74
+ };
75
+ exports.generateSynonym = generateSynonym;
76
+ /**
77
+ * Generate antonyms for the input word.
78
+ */
79
+ const generateAntonym = (word, options) => {
80
+ return generateWords("rel_ant", word, options);
81
+ };
82
+ exports.generateAntonym = generateAntonym;
83
+ /**
84
+ * Generate rhymes for the input word.
85
+ */
86
+ const generateRhyme = (word, options) => {
87
+ return generateWords("rel_rhy", word, options);
88
+ };
89
+ exports.generateRhyme = generateRhyme;
90
+ /**
91
+ * Generate adjectives that are often used to describe the given noun.
92
+ */
93
+ const generateAdjectiveForNoun = (word, options) => {
94
+ return generateWords("rel_jjb", word, options);
95
+ };
96
+ exports.generateAdjectiveForNoun = generateAdjectiveForNoun;
97
+ /**
98
+ * Generate nouns that are often described by the given adjective.
99
+ */
100
+ const generateNounForAdjective = (word, options) => {
101
+ return generateWords("rel_jja", word, options);
102
+ };
103
+ exports.generateNounForAdjective = generateNounForAdjective;
104
+ /**
105
+ * Generate related words using a specific relation code.
106
+ * @param relationCode The Datamuse relation code (e.g., 'rel_trg', 'rel_gen').
107
+ */
108
+ const generateRelatedWord = (word, relationCode, options) => {
109
+ return generateWords(relationCode, word, options);
110
+ };
111
+ exports.generateRelatedWord = generateRelatedWord;
@@ -0,0 +1,2 @@
1
+ export * from "./generators";
2
+ export * from "./utils";
package/dist/index.js ADDED
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./generators"), exports);
18
+ __exportStar(require("./utils"), exports); // Verify if utils should be exported. Original didn't, but exporting types is good.
19
+ // Original index.js only exported generators.
20
+ // "I want to make the full project in TS... also if you can create better logo..."
21
+ // "Also enhance and refactor current code"
22
+ // Exporting types is essential for TS users.
@@ -0,0 +1,37 @@
1
+ import { AxiosResponse } from 'axios';
2
+ export interface DatamuseWord {
3
+ word: string;
4
+ score: number;
5
+ tags?: string[];
6
+ defs?: string[];
7
+ numSyllables?: number;
8
+ }
9
+ export interface GeneratorOptions {
10
+ /**
11
+ * If true, return an array of strings (words) instead of an array of objects.
12
+ * @default false
13
+ */
14
+ transformToArray?: boolean;
15
+ /**
16
+ * Filter result by part-of-speech: 'n' (noun), 'v' (verb), 'adj' (adjective), 'adv' (adverb).
17
+ */
18
+ partOfSpeech?: 'n' | 'v' | 'adj' | 'adv';
19
+ /**
20
+ * Topic words to influence the result.
21
+ */
22
+ topics?: string;
23
+ /**
24
+ * Filter results to words starting with this string/character.
25
+ */
26
+ startWith?: string;
27
+ /**
28
+ * Filter results to words ending with this string/character.
29
+ */
30
+ endWith?: string;
31
+ /**
32
+ * Maximum number of results to return.
33
+ */
34
+ max?: number;
35
+ }
36
+ export declare const wordOptionalParams: (options: GeneratorOptions) => string;
37
+ export declare const decorateWords: (response: AxiosResponse<DatamuseWord[]>, options: GeneratorOptions) => DatamuseWord[] | string[];
@@ -0,0 +1,43 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.decorateWords = exports.wordOptionalParams = void 0;
4
+ const wordOptionalParams = (options) => {
5
+ const { topics, startWith, endWith, max } = options;
6
+ const params = [];
7
+ if (topics) {
8
+ params.push(`topics=${encodeURIComponent(topics)}`);
9
+ }
10
+ if (max) {
11
+ params.push(`max=${max}`);
12
+ }
13
+ const start = startWith || "";
14
+ const end = endWith || "";
15
+ // 'sp' stands for spelled like. Wildcards * are used.
16
+ params.push(`sp=${start}*${end}`);
17
+ // 'md=p' requests part-of-speech tags
18
+ params.push("md=p");
19
+ return params.join('&');
20
+ };
21
+ exports.wordOptionalParams = wordOptionalParams;
22
+ const filterWords = (words, type) => {
23
+ return words.filter((word) => {
24
+ return word.tags && word.tags.includes(type);
25
+ });
26
+ };
27
+ const arrayOfWordsTransformer = (words) => {
28
+ return words.map((w) => w.word);
29
+ };
30
+ const decorateWords = (response, options) => {
31
+ // Extract data safely
32
+ let words = response.data || [];
33
+ // Filter by part of speech if requested
34
+ if (options.partOfSpeech) {
35
+ words = filterWords(words, options.partOfSpeech);
36
+ }
37
+ // Transform to simple array if requested
38
+ if (options.transformToArray) {
39
+ return arrayOfWordsTransformer(words);
40
+ }
41
+ return words;
42
+ };
43
+ exports.decorateWords = decorateWords;
@@ -0,0 +1,111 @@
1
+ import axios from "axios";
2
+ import { wordOptionalParams, decorateWords, GeneratorOptions, DatamuseWord } from "../utils";
3
+
4
+ /**
5
+ * Base function to generate words from Datamuse API.
6
+ * @param queryParam The primary query parameter (e.g., 'ml', 'sl', 'sp', 'rel_syn').
7
+ * @param word The input word.
8
+ * @param options Generator options.
9
+ */
10
+ const generateWords = async (
11
+ queryParam: string,
12
+ word: string,
13
+ options: GeneratorOptions = {}
14
+ ): Promise<DatamuseWord[] | string[]> => {
15
+ try {
16
+ const optionalParams = wordOptionalParams(options);
17
+ const url = `https://api.datamuse.com/words?${queryParam}=${encodeURIComponent(word)}&${optionalParams}`;
18
+
19
+ // Use generic type for axios response
20
+ const response = await axios.get<DatamuseWord[]>(url);
21
+
22
+ return decorateWords(response, options);
23
+ } catch (err) {
24
+ console.error(`Error generating words for ${queryParam}=${word}:`, err);
25
+ return [];
26
+ }
27
+ };
28
+
29
+ /**
30
+ * Generate words that have similar meaning to the input word.
31
+ */
32
+ export const generateWordMeansLike = (word: string, options?: GeneratorOptions) => {
33
+ return generateWords("ml", word, options);
34
+ };
35
+
36
+ /**
37
+ * Generate words that sound like the input word.
38
+ */
39
+ export const generateWordSoundsLike = (word: string, options?: GeneratorOptions) => {
40
+ return generateWords("sl", word, options);
41
+ };
42
+
43
+ /**
44
+ * Generate words that are spelled like the input word.
45
+ */
46
+ export const generateWordSpelledLike = (word: string, options?: GeneratorOptions) => {
47
+ return generateWords("sp", word, options);
48
+ };
49
+
50
+ /**
51
+ * Generate words that appear immediately to the left of the target word in a sentence.
52
+ * (Frequent predecessors)
53
+ */
54
+ export const generateWordHasLeftContext = (word: string, options?: GeneratorOptions) => {
55
+ // 'lc' is the legacy parameter for left context, equivalent to rel_bgb?
56
+ // API docs say 'lc' is "Left Context".
57
+ // We will stick to 'lc' as in original code unless we want to switch to 'rel_bgb'.
58
+ // Let's stick to 'lc' to match exact behavior, but documented as such.
59
+ return generateWords("lc", word, options);
60
+ };
61
+
62
+ /**
63
+ * Generate words that appear immediately to the right of the target word in a sentence.
64
+ * (Frequent followers)
65
+ */
66
+ export const generateWordHasRightContext = (word: string, options?: GeneratorOptions) => {
67
+ return generateWords("rc", word, options);
68
+ };
69
+
70
+ /**
71
+ * Generate synonyms for the input word.
72
+ */
73
+ export const generateSynonym = (word: string, options?: GeneratorOptions) => {
74
+ return generateWords("rel_syn", word, options);
75
+ };
76
+
77
+ /**
78
+ * Generate antonyms for the input word.
79
+ */
80
+ export const generateAntonym = (word: string, options?: GeneratorOptions) => {
81
+ return generateWords("rel_ant", word, options);
82
+ };
83
+
84
+ /**
85
+ * Generate rhymes for the input word.
86
+ */
87
+ export const generateRhyme = (word: string, options?: GeneratorOptions) => {
88
+ return generateWords("rel_rhy", word, options);
89
+ };
90
+
91
+ /**
92
+ * Generate adjectives that are often used to describe the given noun.
93
+ */
94
+ export const generateAdjectiveForNoun = (word: string, options?: GeneratorOptions) => {
95
+ return generateWords("rel_jjb", word, options);
96
+ };
97
+
98
+ /**
99
+ * Generate nouns that are often described by the given adjective.
100
+ */
101
+ export const generateNounForAdjective = (word: string, options?: GeneratorOptions) => {
102
+ return generateWords("rel_jja", word, options);
103
+ };
104
+
105
+ /**
106
+ * Generate related words using a specific relation code.
107
+ * @param relationCode The Datamuse relation code (e.g., 'rel_trg', 'rel_gen').
108
+ */
109
+ export const generateRelatedWord = (word: string, relationCode: string, options?: GeneratorOptions) => {
110
+ return generateWords(relationCode, word, options);
111
+ };
package/index.ts ADDED
@@ -0,0 +1,6 @@
1
+ export * from "./generators";
2
+ export * from "./utils"; // Verify if utils should be exported. Original didn't, but exporting types is good.
3
+ // Original index.js only exported generators.
4
+ // "I want to make the full project in TS... also if you can create better logo..."
5
+ // "Also enhance and refactor current code"
6
+ // Exporting types is essential for TS users.
package/logo-color.png ADDED
Binary file
package/package.json ADDED
@@ -0,0 +1,43 @@
1
+ {
2
+ "name": "@mahmoud_magdy_mahmoud/smart-word-generator",
3
+ "version": "1.1.1",
4
+ "description": "Generate specific words using AI (Datamuse API) depending on your needs. Fully typed with TypeScript.",
5
+ "main": "dist/index.js",
6
+ "types": "dist/index.d.ts",
7
+ "scripts": {
8
+ "build": "tsc",
9
+ "prepublishOnly": "npm run build",
10
+ "test": "echo \"Error: no test specified\" && exit 1"
11
+ },
12
+ "publishConfig": {
13
+ "access": "public"
14
+ },
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git+https://github.com/Mahmoud-Magdy-deeplearning/smart-word-generator.git"
18
+ },
19
+ "keywords": [
20
+ "word",
21
+ "generator",
22
+ "AI",
23
+ "NLP",
24
+ "typescript",
25
+ "datamuse",
26
+ "synonyms",
27
+ "rhymes"
28
+ ],
29
+ "author": "Mahmoud Magdy",
30
+ "license": "ISC",
31
+ "bugs": {
32
+ "url": "https://github.com/Mahmoud-Magdy-deeplearning/smart-word-generator/issues"
33
+ },
34
+ "homepage": "https://github.com/Mahmoud-Magdy-deeplearning/smart-word-generator#readme",
35
+ "dependencies": {
36
+ "axios": "^1.2.1"
37
+ },
38
+ "devDependencies": {
39
+ "@types/node": "^20.0.0",
40
+ "ts-node": "^10.0.0",
41
+ "typescript": "^5.0.0"
42
+ }
43
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,15 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "es2018",
4
+ "module": "commonjs",
5
+ "outDir": "./dist",
6
+ "rootDir": "./",
7
+ "strict": true,
8
+ "esModuleInterop": true,
9
+ "skipLibCheck": true,
10
+ "forceConsistentCasingInFileNames": true,
11
+ "declaration": true
12
+ },
13
+ "include": ["**/*.ts"],
14
+ "exclude": ["node_modules", "dist"]
15
+ }
package/utils/index.ts ADDED
@@ -0,0 +1,89 @@
1
+ import { AxiosResponse } from 'axios';
2
+
3
+ export interface DatamuseWord {
4
+ word: string;
5
+ score: number;
6
+ tags?: string[];
7
+ defs?: string[];
8
+ numSyllables?: number;
9
+ }
10
+
11
+ export interface GeneratorOptions {
12
+ /**
13
+ * If true, return an array of strings (words) instead of an array of objects.
14
+ * @default false
15
+ */
16
+ transformToArray?: boolean;
17
+ /**
18
+ * Filter result by part-of-speech: 'n' (noun), 'v' (verb), 'adj' (adjective), 'adv' (adverb).
19
+ */
20
+ partOfSpeech?: 'n' | 'v' | 'adj' | 'adv';
21
+ /**
22
+ * Topic words to influence the result.
23
+ */
24
+ topics?: string;
25
+ /**
26
+ * Filter results to words starting with this string/character.
27
+ */
28
+ startWith?: string;
29
+ /**
30
+ * Filter results to words ending with this string/character.
31
+ */
32
+ endWith?: string;
33
+ /**
34
+ * Maximum number of results to return.
35
+ */
36
+ max?: number;
37
+ }
38
+
39
+ export const wordOptionalParams = (options: GeneratorOptions): string => {
40
+ const { topics, startWith, endWith, max } = options;
41
+ const params: string[] = [];
42
+
43
+ if (topics) {
44
+ params.push(`topics=${encodeURIComponent(topics)}`);
45
+ }
46
+ if (max) {
47
+ params.push(`max=${max}`);
48
+ }
49
+
50
+ const start = startWith || "";
51
+ const end = endWith || "";
52
+ // 'sp' stands for spelled like. Wildcards * are used.
53
+ params.push(`sp=${start}*${end}`);
54
+
55
+ // 'md=p' requests part-of-speech tags
56
+ params.push("md=p");
57
+
58
+ return params.join('&');
59
+ };
60
+
61
+ const filterWords = (words: DatamuseWord[], type: string): DatamuseWord[] => {
62
+ return words.filter((word) => {
63
+ return word.tags && word.tags.includes(type);
64
+ });
65
+ };
66
+
67
+ const arrayOfWordsTransformer = (words: DatamuseWord[]): string[] => {
68
+ return words.map((w) => w.word);
69
+ };
70
+
71
+ export const decorateWords = (
72
+ response: AxiosResponse<DatamuseWord[]>,
73
+ options: GeneratorOptions
74
+ ): DatamuseWord[] | string[] => {
75
+ // Extract data safely
76
+ let words = response.data || [];
77
+
78
+ // Filter by part of speech if requested
79
+ if (options.partOfSpeech) {
80
+ words = filterWords(words, options.partOfSpeech);
81
+ }
82
+
83
+ // Transform to simple array if requested
84
+ if (options.transformToArray) {
85
+ return arrayOfWordsTransformer(words);
86
+ }
87
+
88
+ return words;
89
+ };