npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@route-optimization/optimizer

v1.0.4

Published

Route optimization integration with Google Route Optimization API and route-optimize-hono backend

Downloads

382

Readme

@route-optimization/optimizer

Route optimization package with support for mock optimization and backend API integration.

Features

  • 🎯 Mock Optimization - Realistic nearest neighbor + 2-opt algorithm for development
  • 🌐 Backend Integration - Connect to route-optimize-hono or Google Route Optimization API
  • 📊 Real-time Status - Track optimization progress with status updates
  • Fast & Efficient - Optimized algorithms for quick results
  • 🔧 Configurable - Flexible vehicle and constraint configuration
  • 📦 Tiny Bundle - Minimal dependencies, tree-shakeable

Installation

npm install @route-optimization/optimizer @route-optimization/core
# or
pnpm add @route-optimization/optimizer @route-optimization/core
# or
yarn add @route-optimization/optimizer @route-optimization/core

Quick Start

Basic Usage (Mock Mode)

import { RouteOptimizer } from '@route-optimization/optimizer';
import type { Stop } from '@route-optimization/core';

// Create optimizer instance (mock mode by default)
const optimizer = new RouteOptimizer({
  mockMode: true,
});

// Define stops
const stops: Stop[] = [
  { id: '1', location: { lat: 13.7563, lng: 100.5018 }, name: 'Bangkok' },
  { id: '2', location: { lat: 13.765, lng: 100.538 }, name: 'Sukhumvit' },
  { id: '3', location: { lat: 13.7467, lng: 100.5348 }, name: 'Silom' },
];

// Optimize route
const result = await optimizer.optimize({ stops });

console.log('Optimized route:', result.routes[0]);
console.log('Total distance:', result.metrics.totalDistance, 'meters');
console.log('Total duration:', result.metrics.totalDuration, 'seconds');

With Backend API

const optimizer = new RouteOptimizer({
  mockMode: false,
  backend: {
    apiUrl: 'https://your-backend.com/api',
    apiToken: 'your-api-token',
    timeout: 30000,
  },
});

const result = await optimizer.optimize({
  stops,
  vehicle: {
    capacity: [{ type: 'weight', value: 1000, unit: 'kg' }],
    costPerKm: 5,
    costPerHour: 50,
  },
  constraints: {
    mode: 'balanced',
    considerTraffic: true,
  },
});

Track Optimization Progress

// Subscribe to status updates
const unsubscribe = optimizer.onStatusChange((status) => {
  console.log(`Status: ${status.status}, Progress: ${status.progress}%`);
  console.log(`Message: ${status.message}`);
});

// Optimize
await optimizer.optimize({ stops });

// Cleanup
unsubscribe();

API Reference

RouteOptimizer

Main optimizer class for route optimization.

Constructor

new RouteOptimizer(config?: OptimizerConfig)

Config Options:

  • mockMode?: boolean - Use mock optimization (default: true)
  • backend?: BackendConfig - Backend API configuration
  • defaultVehicle?: VehicleConfig - Default vehicle settings
  • defaultConstraints?: OptimizationConstraints - Default constraints

Methods

optimize(request: OptimizationRequest): Promise<OptimizationResult>

Optimize a route with given stops.

const result = await optimizer.optimize({
  stops: [...],
  vehicle: { /* vehicle config */ },
  constraints: { /* constraints */ },
  mockMode: true, // Override config
});
onStatusChange(listener: (status: OptimizationStatus) => void): () => void

Subscribe to optimization status updates. Returns unsubscribe function.

const unsubscribe = optimizer.onStatusChange((status) => {
  console.log(status.status, status.progress);
});
getStatus(): OptimizationStatus

Get current optimization status.

updateConfig(config: Partial<OptimizerConfig>): void

Update optimizer configuration.

Types

OptimizationRequest

interface OptimizationRequest {
  stops: Stop[];
  vehicle?: VehicleConfig;
  constraints?: OptimizationConstraints;
  mockMode?: boolean;
}

OptimizationResult

interface OptimizationResult {
  routes: Route[];
  metrics: OptimizationMetrics;
  request: OptimizationRequest;
  computeTime: number;
}

OptimizationMetrics

interface OptimizationMetrics {
  totalDistance: number; // meters
  totalDuration: number; // seconds
  totalCost?: number;
  stopsServed: number;
  routeCount: number;
  improvement?: number; // percentage
}

VehicleConfig

interface VehicleConfig {
  startLocation?: { lat: number; lng: number };
  endLocation?: { lat: number; lng: number };
  capacity?: CapacityConstraint[];
  costPerKm?: number;
  costPerHour?: number;
  maxRouteDuration?: number;
  maxRouteDistance?: number;
}

OptimizationConstraints

interface OptimizationConstraints {
  timeWindows?: boolean;
  considerTraffic?: boolean;
  mode?: 'fastest' | 'shortest' | 'balanced';
  allowMultipleRoutes?: boolean;
}

Mock Optimization Algorithm

The mock optimizer uses a realistic nearest neighbor algorithm with 2-opt improvement:

  1. Nearest Neighbor: Start from depot, visit nearest unvisited stop iteratively
  2. 2-opt Improvement: Eliminate route crossings by reversing segments
  3. Distance Calculation: Haversine formula for accurate distances
  4. Metrics: Realistic duration (30 km/h avg) and cost calculations

This provides realistic optimization for development and testing without external API calls.

Backend Integration

route-optimize-hono Backend

Configure to use your route-optimize-hono backend:

const optimizer = new RouteOptimizer({
  mockMode: false,
  backend: {
    apiUrl: 'http://localhost:3000/api',
    apiToken: process.env.API_TOKEN,
  },
});

Expected Backend API Format

POST /optimize

Request:

{
  "stops": [{ "id": "1", "location": { "lat": 13.7563, "lng": 100.5018 }, "name": "Stop 1" }],
  "vehicle": { "capacity": [{ "type": "weight", "value": 1000 }] },
  "constraints": { "mode": "balanced" }
}

Response:

{
  "routes": [...],
  "metrics": {
    "totalDistance": 15000,
    "totalDuration": 1800,
    "stopsServed": 5,
    "routeCount": 1
  },
  "computeTime": 1234
}

Examples

See the examples directory for complete implementations:

  • React: examples/react-example
  • Vue 3: examples/vue3-basic
  • Vanilla JS: examples/vanilla-basic

License

MIT © ks-arm