Skip to content

Commit 1bfc126

Browse files
committed
feat: add addArticle function
1 parent d666063 commit 1bfc126

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

src/runtime/utils/text.ts

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -213,3 +213,46 @@ export const getLanguageName = (
213213
return languageCode // Fallback to the input code if an error occurs
214214
}
215215
}
216+
217+
/**
218+
* Determines the correct indefinite article ("a" or "an") for a given string
219+
* and optionally prepends it to the string.
220+
*
221+
* @param text The input string for which to determine the article.
222+
* @param includeText If true (default), returns the article followed by the original text (e.g., "an apple").
223+
* If false, returns only the article (e.g., "an").
224+
* @returns The determined article, optionally with the original text, or an empty string
225+
* if the input text is empty and includeText is false, or the original text if empty and includeText is true.
226+
*/
227+
export function addArticle(
228+
text: string | undefined,
229+
includeText = true,
230+
): string {
231+
// Handle empty string case first
232+
if (!text) return ''
233+
234+
const firstLetter = text[0].toLowerCase()
235+
// Extended list of vowels for basic check.
236+
// Does not handle phonetic exceptions like "hour" (needs "an") or "university" (needs "a").
237+
const vowels: string[] = ['a', 'e', 'i', 'o', 'u']
238+
let article: string
239+
240+
if (vowels.includes(firstLetter)) {
241+
article = 'an'
242+
}
243+
else {
244+
// A more complex check could be added here for numbers that sound like they start with a vowel,
245+
// e.g., "8" (an eight), "11" (an eleven).
246+
// For simplicity, this version treats numbers starting with '1', '8' etc., based on their first character's type.
247+
// If the first char is a digit that isn't 'a,e,i,o,u', it gets 'a'.
248+
// This is a common simplification.
249+
article = 'a'
250+
}
251+
252+
if (includeText) {
253+
return `${article} ${text}`
254+
}
255+
else {
256+
return article
257+
}
258+
}

0 commit comments

Comments
 (0)