TechDoc Hub
← Back to Home

Code Examples

Practical code snippets and implementation examples

Featured Code Examples

Binary Search Algorithm

Efficient search algorithm for sorted arrays

JavaScript
Complexity: O(log n)
AlgorithmSearchArray
Code
function binarySearch(arr, target) {
    let left = 0;
    let right = arr.length - 1;
    
    while (left <= right) {
        const mid = Math.floor((left + right) / 2);
        
        if (arr[mid] === target) {
            return mid;
        } else if (arr[mid] < target) {
            left = mid + 1;
        } else {
            right = mid - 1;
        }
    }
    
    return -1; // Not found
}

// Usage
const numbers = [1, 3, 5, 7, 9, 11, 13];
console.log(binarySearch(numbers, 7)); // Output: 3

React Custom Hook - useLocalStorage

Custom hook for managing localStorage in React

TypeScript
Complexity: O(1)
ReactHooklocalStorageTypeScript
Code
import { useState, useEffect } from 'react';

function useLocalStorage<T>(key: string, initialValue: T) {
    // Get value from localStorage or use initial value
    const [storedValue, setStoredValue] = useState<T>(() => {
        try {
            const item = window.localStorage.getItem(key);
            return item ? JSON.parse(item) : initialValue;
        } catch (error) {
            console.error('Error reading localStorage:', error);
            return initialValue;
        }
    });

    // Update localStorage when state changes
    const setValue = (value: T | ((val: T) => T)) => {
        try {
            const valueToStore = value instanceof Function 
                ? value(storedValue) 
                : value;
            setStoredValue(valueToStore);
            window.localStorage.setItem(key, JSON.stringify(valueToStore));
        } catch (error) {
            console.error('Error setting localStorage:', error);
        }
    };

    return [storedValue, setValue] as const;
}

// Usage
function UserProfile() {
    const [user, setUser] = useLocalStorage('user', { name: '', email: '' });
    
    return (
        <div>
            <input 
                value={user.name}
                onChange={(e) => setUser({...user, name: e.target.value})}
                placeholder="Name"
            />
        </div>
    );
}

Debounce Function

Utility function to limit function execution frequency

JavaScript
Complexity: O(1)
UtilityPerformanceEvent Handling
Code
function debounce(func, delay) {
    let timeoutId;
    
    return function (...args) {
        // Clear existing timeout
        clearTimeout(timeoutId);
        
        // Set new timeout
        timeoutId = setTimeout(() => {
            func.apply(this, args);
        }, delay);
    };
}

// Usage with search input
const searchInput = document.getElementById('search');
const handleSearch = debounce((query) => {
    console.log('Searching for:', query);
    // Perform API call here
}, 300);

searchInput.addEventListener('input', (e) => {
    handleSearch(e.target.value);
});

// React version
import { useCallback } from 'react';

function useDebounce(callback, delay) {
    const [timeoutId, setTimeoutId] = useState(null);
    
    return useCallback((...args) => {
        if (timeoutId) clearTimeout(timeoutId);
        
        const newTimeoutId = setTimeout(() => {
            callback(...args);
        }, delay);
        
        setTimeoutId(newTimeoutId);
    }, [callback, delay, timeoutId]);
}

Tips for Using Code Examples

Understand First

Don't just copy-paste. Understand how and why the code works.

Adapt & Modify

Modify examples to fit your specific use case and requirements.

Test Thoroughly

Always test code examples in your environment before using in production.

Learn Patterns

Focus on learning patterns and concepts, not just specific implementations.