I have developed a function to search for blog posts, prioritizing titles over excerpts and excerpts over content when added to the containsQuery array. While the code seems to be working well, I have noticed that there is a lot of redundant code. How can I streamline this process?
const findArticles = (posts: any[], query: string) => {
const containsQuery: any[] = []
let words
let i: number
if (query.includes(' ')) {
words = query.toLowerCase().split(' ')
}
const findArticle = (multipleWords:boolean, posts: any[], query:string, searchedParam:string, words:string[] = [],) => {
if (multipleWords === false) {
for (i = 0; i < posts.length; i++) {
if (posts[i][`${searchedParam}`].toLowerCase().includes(query.toLowerCase())) {
containsQuery.push(posts[i])
}
}
} else {
for (i = 0; i < posts.length; i++) {
if(words.every(q => posts[i][`${searchedParam}`].toLowerCase().includes(q))) {
containsQuery.push(posts[i])
}
}
}
}
if (words) {
findArticle(true, posts, query, 'title', words,)
} else {
findArticle(false, posts, query, 'title')
}
if (words) {
findArticle(true, posts, query, 'excerpt', words,)
} else {
findArticle(false, posts, query, 'excerpt')
}
if (words) {
findArticle(true, posts, query, 'content', words,)
} else {
findArticle(false, posts, query, 'content')
}
const oneOfKind = Array.from(new Set(containsQuery.map(article => article.id))).map(id => {
return containsQuery.find(a => a.id === id)
})
return oneOfKind
}
To avoid duplicates and improve efficiency, I attempted to create a copy of the posts using my own const copyOfPosts = posts and then modify it, but this caused some issues in the code. The current code structure appears to be the most effective way to achieve the desired outcome. Any suggestions for improvement are greatly appreciated.
if (posts[i][`${searchedParam}`].toLowerCase().includes(query.toLowerCase())) {
containsQuery.push(posts[i])
copyOfPosts.splice(i, 1)
}