Enhance search index handling by returning an empty array for no results instead of throwing an error. Improve memory management in free_words function by checking for NULL before freeing. Update search_index to properly return NULL when no results are found.
This commit is contained in:
@@ -48,7 +48,9 @@ int split_into_words(const char *s,
|
||||
|
||||
// Free memory allocated for words
|
||||
void free_words(char *storage) { /* simplified */
|
||||
free(storage); /* single free, if any */
|
||||
if (storage) { /* check for NULL */
|
||||
free(storage); /* single free, if any */
|
||||
}
|
||||
}
|
||||
|
||||
// Calculate Levenshtein distance between two strings
|
||||
@@ -105,7 +107,7 @@ float word_similarity(const char *word1, const char *word2) {
|
||||
// Calculate similarity between query and target string
|
||||
float calculate_similarity(const char *query, const char *target, float cutoff) {
|
||||
// Split strings into words
|
||||
char *query_buf, *target_buf;
|
||||
char *query_buf = NULL, *target_buf = NULL;
|
||||
char *query_words[MAX_WORDS], *target_words[MAX_WORDS];
|
||||
|
||||
int query_word_count = split_into_words(query, query_words, &query_buf);
|
||||
@@ -304,6 +306,12 @@ SearchResult* search_index(SearchIndex* index, const char* query, float cutoff,
|
||||
}
|
||||
}
|
||||
|
||||
// If no results found, return NULL properly
|
||||
if (*num_results == 0) {
|
||||
free(temp_results);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
// Sort results by similarity
|
||||
qsort(temp_results, *num_results, sizeof(SearchResult), compare_results);
|
||||
|
||||
|
||||
@@ -129,9 +129,9 @@ Napi::Value SearchIndexWrapper::Search(const Napi::CallbackInfo& info) {
|
||||
int num_results = 0;
|
||||
SearchResult* results = search_index(this->index_, query.c_str(), cutoff, &num_results);
|
||||
|
||||
if (!results) {
|
||||
Napi::Error::New(env, "Search failed").ThrowAsJavaScriptException();
|
||||
return env.Null();
|
||||
// If no results found, return empty array instead of throwing error
|
||||
if (!results || num_results == 0) {
|
||||
return Napi::Array::New(env, 0);
|
||||
}
|
||||
|
||||
Napi::Array result_array = Napi::Array::New(env, num_results);
|
||||
|
||||
Reference in New Issue
Block a user