🔍 Client-Side Search = Instant Results
Users expect instant search results. JavaScript array methods enable fast client-side search with fuzzy matching and filtering.
📝 Search Engine Implementation
class SearchEngine {
constructor(data, options = {}) {
this.data = data;
this.options = {
keys: options.keys || ['title', 'description'],
threshold: options.threshold || 0.3,
maxResults: options.maxResults || 50,
caseSensitive: options.caseSensitive || false
};
}
search(query) {
if (!query || query.trim().length === 0) {
return [];
}
const searchTerm = this.options.caseSensitive
? query.trim()
: query.trim().toLowerCase();
const results = this.data
.map(item => ({
item,
score: this.calculateScore(item, searchTerm)
}))
.filter(result => result.score > 0)
.sort((a, b) => b.score - a.score)
.slice(0, this.options.maxResults)
.map(result => ({
...result.item,
_score: result.score
}));
return results;
}
calculateScore(item, searchTerm) {
let totalScore = 0;
const searchWords = searchTerm.split(' ');
for (const key of this.options.keys) {
const value = this.getValue(item, key);
if (!value) continue;
const text = this.options.caseSensitive
? value
: value.toLowerCase();
if (text === searchTerm) {
totalScore += 100;
}
if (text.includes(searchTerm)) {
totalScore += 50;
}
const words = text.split(' ');
for (const word of searchWords) {
if (words.some(w => w.includes(word))) {
totalScore += 10;
}
}
if (text.startsWith(searchTerm)) {
totalScore += 30;
}
const distance = this.levenshteinDistance(text, searchTerm);
const maxLength = Math.max(text.length, searchTerm.length);
if (maxLength > 0) {
const similarity = 1 - (distance / maxLength);
if (similarity > this.options.threshold) {
totalScore += similarity * 20;
}
}
}
return totalScore;
}
getValue(item, path) {
return path.split('.').reduce((obj, key) =>
obj && obj[key] !== undefined ? obj[key] : null, item
);
}
levenshteinDistance(str1, str2) {
if (str1.length === 0) return str2.length;
if (str2.length === 0) return str1.length;
const matrix = [];
for (let i = 0; i <= str1.length; i++) {
matrix[i] = [i];
}
for (let j = 0; j <= str2.length; j++) {
matrix[0][j] = j;
}
for (let i = 1; i <= str1.length; i++) {
for (let j = 1; j <= str2.length; j++) {
const cost = str1[i - 1] === str2[j - 1] ? 0 : 1;
matrix[i][j] = Math.min(
matrix[i - 1][j] + 1,
matrix[i][j - 1] + 1,
matrix[i - 1][j - 1] + cost
);
}
}
return matrix[str1.length][str2.length];
}
getSuggestions(query, limit = 5) {
if (!query || query.trim().length === 0) {
return [];
}
const suggestions = new Set();
const searchTerm = query.trim().toLowerCase();
for (const item of this.data) {
for (const key of this.options.keys) {
const value = this.getValue(item, key);
if (!value) continue;
const text = value.toLowerCase();
if (text.includes(searchTerm)) {
const words = text.split(' ');
for (const word of words) {
if (word.toLowerCase().includes(searchTerm)
&& word.length > 2) {
suggestions.add(word);
}
}
}
}
if (suggestions.size >= limit * 2) break;
}
return Array.from(suggestions).slice(0, limit);
}
}
const products = [
{ id: 1, title: 'Wireless Headphones', category: 'Electronics', price: 99 },
{ id: 2, title: 'Smart Watch', category: 'Electronics', price: 199 },
{ id: 3, title: 'Running Shoes', category: 'Sports', price: 89 },
{ id: 4, title: 'Coffee Mug', category: 'Kitchen', price: 15 },
{ id: 5, title: 'Backpack', category: 'Fashion', price: 45 }
];
const searchEngine = new SearchEngine(products, {
keys: ['title', 'category'],
threshold: 0.2,
maxResults: 10
});
const debounce = (fn, delay) => {
let timeout;
return (...args) => {
clearTimeout(timeout);
timeout = setTimeout(() => fn(...args), delay);
};
};
const performSearch = debounce((query) => {
const results = searchEngine.search(query);
const suggestions = searchEngine.getSuggestions(query);
renderResults(results);
renderSuggestions(suggestions);
}, 300);
🎯 Performance Optimization
class SearchIndex {
constructor(data, keys) {
this.index = new Map();
this.data = data;
this.keys = keys;
this.buildIndex();
}
buildIndex() {
for (const item of this.data) {
for (const key of this.keys) {
const value = this.getValue(item, key);
if (!value) continue;
const words = value.toLowerCase().split(' ');
for (const word of words) {
if (!this.index.has(word)) {
this.index.set(word, []);
}
if (!this.index.get(word).includes(item)) {
this.index.get(word).push(item);
}
}
}
}
}
search(query) {
const words = query.toLowerCase().split(' ');
const results = [];
const seen = new Set();
for (const word of words) {
const items = this.index.get(word) || [];
for (const item of items) {
if (!seen.has(item)) {
seen.add(item);
results.push(item);
}
}
}
return results;
}
getValue(item, path) {
return path.split('.').reduce((obj, key) =>
obj && obj[key] !== undefined ? obj[key] : null, item
);
}
}
💡 Search Optimization Tips
- Build search index for faster lookups
- Use debouncing for instant search
- Implement fuzzy matching for typos
- Provide auto-complete suggestions
- Use Web Workers for large datasets
Client-side search with fuzzy matching creates a delightful user experience. Instant results and intelligent suggestions make users feel understood.
