Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use weight on search #521

Closed
mateusfg7 opened this issue May 29, 2023 · 0 comments
Closed

Use weight on search #521

mateusfg7 opened this issue May 29, 2023 · 0 comments
Labels
feat New feature or request lint/refactor Refactor or Lint code for facility the maintenance

Comments

@mateusfg7
Copy link
Owner

mateusfg7 commented May 29, 2023

Use a weight system to better search, something like this:

import { Post } from 'contentlayer/generated'
import { slug } from '@/shared/lib/slug'

export function searchMath(post: Post, search: string) {
  const sluggedSearch = slug(search)

  let weight = 0

  if (slug(post.title).includes(sluggedSearch)) weight++
  if (slug(post.description).includes(sluggedSearch)) weight++
  if (slug(post.author).includes(sluggedSearch)) weight++
  if (slug(post.category).includes(sluggedSearch)) weight++
  if (slug(post.status).includes(sluggedSearch)) weight++
  if (slug(post.tags).includes(sluggedSearch)) weight++

  return weight
}

Then, sort results by weight value, from biggest to smallest, and remove results with value 0.

Also add an array of sources for match, and map to it for match condition:

import { Post } from 'contentlayer/generated'
import { slug } from '@/shared/lib/slug'

export function searchMath(post: Post, search: string) {
  const sluggedSearch = slug(search)

  let weight = 0
  const sources = [post.title, post.description, post.author, post.category, post.status, post.tags]

  sources.forEach(source => slug(post.title).includes(sluggedSearch) && weight++)

  return weight
}
@mateusfg7 mateusfg7 added feat New feature or request lint/refactor Refactor or Lint code for facility the maintenance labels May 29, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
feat New feature or request lint/refactor Refactor or Lint code for facility the maintenance
Projects
None yet
Development

No branches or pull requests

1 participant