Back to Repositories

Testing Linear Search Algorithm Implementation in javascript-algorithms

This test suite validates the linear search algorithm implementation across different data types and scenarios in JavaScript. It ensures the search function correctly handles arrays of numbers, strings, and objects while properly returning matching indices.

Test Coverage Overview

The test suite provides comprehensive coverage of linear search functionality across multiple data types.

Key areas tested include:
  • Numeric array searches with single and multiple matches
  • String array searches with varying occurrences
  • Object array searches using custom comparator functions
  • Edge cases with non-existent elements

Implementation Analysis

The testing approach uses Jest’s describe/it pattern for structured test organization. Each test case validates the linearSearch function’s ability to return correct array indices for matching elements.

Technical implementation features:
  • Custom comparator callback for object comparison
  • Array index tracking for multiple matches
  • Type-agnostic search capabilities

Technical Details

Testing infrastructure includes:
  • Jest testing framework
  • ES6 module import/export syntax
  • Array-based test fixtures
  • Custom object comparator functions
  • Expect assertions for array equality

Best Practices Demonstrated

The test suite exemplifies several testing best practices for algorithm validation.

Notable practices include:
  • Isolated test cases for different data types
  • Clear test descriptions and expectations
  • Comprehensive edge case coverage
  • Modular test organization
  • Consistent assertion patterns

trekhleb/javascript-algorithms

src/algorithms/search/linear-search/__test__/linearSearch.test.js

            
import linearSearch from '../linearSearch';

describe('linearSearch', () => {
  it('should search all numbers in array', () => {
    const array = [1, 2, 4, 6, 2];

    expect(linearSearch(array, 10)).toEqual([]);
    expect(linearSearch(array, 1)).toEqual([0]);
    expect(linearSearch(array, 2)).toEqual([1, 4]);
  });

  it('should search all strings in array', () => {
    const array = ['a', 'b', 'a'];

    expect(linearSearch(array, 'c')).toEqual([]);
    expect(linearSearch(array, 'b')).toEqual([1]);
    expect(linearSearch(array, 'a')).toEqual([0, 2]);
  });

  it('should search through objects as well', () => {
    const comparatorCallback = (a, b) => {
      if (a.key === b.key) {
        return 0;
      }

      return a.key <= b.key ? -1 : 1;
    };

    const array = [
      { key: 5 },
      { key: 6 },
      { key: 7 },
      { key: 6 },
    ];

    expect(linearSearch(array, { key: 10 }, comparatorCallback)).toEqual([]);
    expect(linearSearch(array, { key: 5 }, comparatorCallback)).toEqual([0]);
    expect(linearSearch(array, { key: 6 }, comparatorCallback)).toEqual([1, 3]);
  });
});