Sorting framework basid on best design patterns with the most powerful sort strategies in TypeScript
npm install the-best-sortA comprehensive AI-friendly TypeScript library for array sorting and asynchronous processing using powerful strategy with advanced object-oriented programming patterns and design principles.
The Best Sort is a production-ready TypeScript framework designed to handle efficient sorting operations at scale. At its core, it implements a powerful asynchronous sleep sort strategy, enabling you to sort large datasets with concurrent processing capabilities. The framework leverages event-driven architecture to provide real-time observability into sorting progress, making it practical for production environments where monitoring and performance insights matter.
Whether you're sorting massive collections, processing data streams, or integrating sorting into AI agent workflows, The Best Sort delivers type-safe, extensible sorting solutions. Built with modern software engineering practices, it provides both a reliable tool for practical sorting tasks and a learning resource for developers seeking to understand how sophisticated sorting systems are implemented in contemporary applications.
- Node.js 18.0.0 or higher
- npm or yarn
Clone the repository and install dependencies:
``sh`
npm install -D typescript @types/node
`sh`
npm install -D tsx
npx tsx src/index.ts
`sh`
npx tsc src/index.ts --experimentalDecorators --emitDecoratorMetadata
node the-best-sort.js
The Best Sort implements multiple design patterns to create a robust and extensible framework, including singleton, factory, builder, facade, decorators, strategy, observer, command invoker and runner so you can implement flexible, adaptive sorting solutions for any dataset.
A comparable number wrapper implementing the ISortableNumber interface:
`typescript
import { SortableNumber } from "the-best-sort";
const nums = [1, 2, 3].map(n => new SortableNumber(n));
`
Manages state and event notifications during visualization:
`typescript
import { SortableNumber, SortingContext } from "the-best-sort";
const context = new SortingContext
context.attach(observer);
context.emitElementDisplayed(element, index, delay);
`
Create sorting strategies through the factory:
`typescript
import { SortableNumber, ConcreteSortingStrategyFactory, StrategyType } from "the-best-sort";
const factory = new ConcreteSortingStrategyFactory
const strategy = factory.createStrategy(StrategyType.DEFAULT);
`
Track visualization events and collect metrics:
`typescript
import { SortableNumber, StatisticsObserver, HistoryObserver } from "the-best-sort";
const statsObserver = new StatisticsObserver
const historyObserver = new HistoryObserver
sorter.addObserver(statsObserver);
sorter.addObserver(historyObserver);
`
Control visualization behavior globally:
`typescript
import { ConfigurationManager } from "the-best-sort";
ConfigurationManager.getInstance().updateConfig({
baseDelayMs: 100,
enableLogging: true,
showTimestamps: true,
colorize: true
});
`
The library emits the following event types during sorting:
- STARTED - Sorting has startedELEMENT_SORTED
- - An array element was processed and added to resultCOMPLETED
- - Sorting has completedERROR
- - An error occurred during sorting
StatisticsObserver collects the following metrics:
`typescript`
interface SortingStatistics {
duration: number; // Total duration in milliseconds
sortedElements: number; // Number of elements sorted
totalDelay: number; // Sum of all delays
averageDelay: number; // Average delay per element
eventCounts: Map
}
The library follows a layered architecture:
1. Core Domain - SortableNumber, event types, configurationSortingContext
2. Patterns Layer - Decorators, strategies, factory implementations
3. Context Layer - managing state and notificationsArraySorter
4. Observer Layer - Multiple observer implementations (Console, Statistics, History)
5. Application Layer - , CommandInvoker, runners
6. Factory Layer - Strategy and builder creation
- Generics for type-safe implementations
- Decorators for cross-cutting concerns
- Abstract classes and interfaces for contracts
- Union types and enums for type safety
- Method decorators with property descriptors
- Readonly types for immutability
- Object destructuring and spreading
Basic usage:
`typescript
import { SortableNumber, ConcreteSortingStrategyFactory, StrategyType, SorterBuilder } from "the-best-sort";
const numbers = [1, 100, 10];
const sortableArray = numbers.map(n => new SortableNumber(n));
const factory = new ConcreteSortingStrategyFactory
const strategy = factory.createStrategy(StrategyType.DEFAULT);
const sorter = new SorterBuilder
.setArray(sortableArray)
.setStrategy(strategy)
.build();
const sortedArray = await sorter.execute();
console.log(sortedArray)
`
`typescript
import { SortableNumber, ConcreteSortingStrategyFactory, StrategyType, SorterBuilder, StatisticsObserver, HistoryObserver } from "the-best-sort";
const statisticsObserver = new StatisticsObserver
const historyObserver = new HistoryObserver
const sorter = new SorterBuilder
.setArray(sortableArray)
.setStrategy(strategy)
.addObserver(statisticsObserver)
.addObserver(historyObserver)
.build();
await sorter.execute();
statisticsObserver.printStatistics();
historyObserver.printHistory();
`
`typescript
import { CommandInvoker, ExecuteSortingCommand } from "the-best-sort";
const invoker = new CommandInvoker();
const sortingCommand = new ExecuteSortingCommand(sorter);
invoker.enqueueCommand(sortingCommand);
const results = await invoker.executeAll();
`
`typescript
import { LoggingSortingRunner } from "the-best-sort";
const runner = new LoggingSortingRunner
const sortedArray = await runner.run(sortableArray, StrategyType.DEFAULT);
`
`typescript
import { ISortable, IObserver, SortingEvent, EventType } from "the-best-sort";
class MetricsObserver
update(event: SortingEvent
if (event.type === EventType.ELEMENT_SORTED) {
// Custom logic here
}
}
}
sorter.addObserver(new MetricsObserver());
`
`typescript
import { ISortable, AbstractSortingStrategy, SortingContext, StrategyType } from "the-best-sort";
class BubbleSortStrategy
extends AbstractSortingStrategy
sort(array: T[], context: SortingContext
context.emitStarted();
// Implementation
context.emitCompleted();
return Promise.resolve(result);
}
getName(): string {
return 'Bubble Sort Strategy';
}
getDescription(): string {
return 'Classic bubble sort implementation';
}
}
// Register strategy
factory.registerStrategy(StrategyType.BUBBLE, new BubbleSortStrategy());
`
`typescript
import { ICommand, ConfigurationManager } from "the-best-sort";
class ResetCommand implements ICommand {
async execute(): Promise
ConfigurationManager.getInstance().resetToDefaults();
}
getDescription(): string {
return 'Reset configuration to defaults';
}
}
invoker.enqueueCommand(new ResetCommand());
`
`typescript
import { ISortable, AbstractSortingRunner } from "the-best-sort";
class MetricsSortingRunner
extends AbstractSortingRunner
protected beforeRun(): void {
console.log('Initializing sorting with metrics...');
}
protected afterRun(): void {
console.log('Sorting completed with full metrics');
}
}
const runner = new MetricsSortingRunner
const result = await runner.run(sortableArray, StrategyType.DEFAULT);
`
- TypeScript 4.7 or higher
- Node.js 18.0.0 or higher
- Decorator support enabled in tsconfig.json`
- Very large arrays (10,000+) may cause performance degradation
Contributions are welcome. Please ensure all code follows the established patterns and includes appropriate type annotations.
For issues, questions, or feature requests, please open an issue in the repository.