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 🙏

© 2026 – Pkg Stats / Ryan Hefner

@digitaldefiance/luhn-mod-n

v1.0.0

Published

Enterprise-grade LUHN Modulo N algorithm implementation for TypeScript with support for bases 2-16

Downloads

9

Readme

Luhn Mod N - TypeScript

Enterprise-grade LUHN Modulo N algorithm implementation for TypeScript with support for bases 2-16.

Improved from https://github.com/Digital-Defiance/Luhn-mod-n which is itself improved from https://stackoverflow.com/a/23640453.

Features

  • Multiple Input Types: Array, String, Number, and BigInt support
  • Flexible Base Support: Works with bases 2 through 16
  • Type-Safe: Full TypeScript support with interfaces and generics
  • Enterprise Architecture: SOLID principles, dependency injection, factory pattern
  • Comprehensive Testing: 100% test coverage with unit and integration tests
  • Error Detection: Detects single-digit errors and transposition errors
  • Zero Dependencies: No external runtime dependencies

Installation

yarn install

Quick Start

import { LuhnServiceFactory } from 'luhn-mod-n-ts';

// Create a service for your data type
const service = LuhnServiceFactory.createStringService();

// Calculate check digit
const checkDigit = service.calculate('123'); // Returns: 0

// Append check digit
const withCheck = service.append('123'); // Returns: '1230'

// Validate
const isValid = service.validate('1230'); // Returns: true

Usage

Array Service

import { LuhnServiceFactory } from 'luhn-mod-n-ts';

const arrayService = LuhnServiceFactory.createArrayService();

// Base 10 (default)
arrayService.calculate([1, 2, 3]); // 0
arrayService.append([1, 2, 3]); // [1, 2, 3, 0]
arrayService.validate([1, 2, 3, 0]); // true

// Base 16
arrayService.calculate([15, 14, 13], 16); // 14
arrayService.append([15, 14, 13], 16); // [15, 14, 13, 14]
arrayService.validate([15, 14, 13, 14], 16); // true

String Service

import { LuhnServiceFactory } from 'luhn-mod-n-ts';

const stringService = LuhnServiceFactory.createStringService();

// Base 10
stringService.calculate('123'); // 0
stringService.append('123'); // '1230'
stringService.validate('1230'); // true

// Base 16 (hexadecimal)
stringService.calculate('abc', 16); // 2
stringService.append('abc', 16); // 'abc2'
stringService.validate('abc2', 16); // true

Number Service

import { LuhnServiceFactory } from 'luhn-mod-n-ts';

const numberService = LuhnServiceFactory.createNumberService();

numberService.calculate(123); // 0
numberService.append(123); // 1230
numberService.validate(1230); // true

BigInt Service

import { LuhnServiceFactory } from 'luhn-mod-n-ts';

const bigIntService = LuhnServiceFactory.createBigIntService();

// Handle very large numbers
const largeNumber = 123456789012345678901234567890n;
const withCheck = bigIntService.append(largeNumber);
bigIntService.validate(withCheck); // true

Real-World Examples

Credit Card Validation

const service = LuhnServiceFactory.createStringService();

// Add check digit to card number
const cardNumber = '7992739871';
const withCheck = service.append(cardNumber);
console.log(withCheck); // '79927398713'

// Validate card number
if (service.validate(withCheck)) {
  console.log('Valid card number');
}

Serial Number Generation

const service = LuhnServiceFactory.createNumberService();

// Generate serial with check digit
const serial = 987654321;
const validSerial = service.append(serial);
console.log(validSerial); // 9876543217

Hexadecimal Identifiers

const service = LuhnServiceFactory.createStringService();

// Create hex ID with check digit
const hexId = 'deadbeef';
const validId = service.append(hexId, 16);
console.log(validId); // 'deadbeef3'

Architecture

The library follows enterprise design patterns:

luhn-mod-n-ts/
├── core/
│   └── luhn-algorithm.ts       # Core Luhn algorithm
├── services/
│   └── check-digit-service.ts  # Generic service layer
├── converters/
│   └── digit-converters.ts     # Type conversion strategies
├── validators/
│   └── base-validator.ts       # Input validation
├── factories/
│   └── luhn-service-factory.ts # Service creation
├── interfaces.ts               # TypeScript interfaces
├── errors.ts                   # Custom error types
└── index.ts                    # Public API

Key Components

  • LuhnAlgorithm: Core algorithm implementation
  • CheckDigitService: Generic service for any type
  • DigitConverters: Strategy pattern for type conversions
  • BaseValidator: Input validation with custom ranges
  • LuhnServiceFactory: Factory for creating type-specific services

Advanced Usage

Custom Service Creation

import { 
  CheckDigitService, 
  LuhnAlgorithm, 
  BaseValidator,
  StringDigitConverter 
} from 'luhn-mod-n-ts';

// Create custom service with base 16 default
const validator = new BaseValidator();
const algorithm = new LuhnAlgorithm(validator);
const converter = new StringDigitConverter();
const service = new CheckDigitService(algorithm, converter, 16);

// Now base 16 is default
service.append('abc'); // 'abc2' (no need to specify base)

Custom Base Range

import { BaseValidator, LuhnAlgorithm } from 'luhn-mod-n-ts';

// Only allow bases 8-12
const validator = new BaseValidator(8, 12);
const algorithm = new LuhnAlgorithm(validator);

API Reference

LuhnServiceFactory

Static factory for creating services:

  • createArrayService(): Returns CheckDigitService<number[]>
  • createStringService(): Returns CheckDigitService<string>
  • createNumberService(): Returns CheckDigitService<number>
  • createBigIntService(): Returns CheckDigitService<bigint>

CheckDigitService

Generic service with three methods:

  • calculate(value: T, base?: number): number - Calculate check digit
  • append(value: T, base?: number): T - Append check digit to value
  • validate(value: T, base?: number): boolean - Validate value with check digit

Error Types

  • InvalidBaseError: Thrown when base is outside valid range
  • InvalidInputError: Thrown for invalid input (e.g., empty string)

Testing

# Run all tests
yarn test

# Watch mode
yarn test:watch

# Coverage report
yarn test:coverage

Test Coverage

  • ✅ Core algorithm (all bases 2-16)
  • ✅ All converters (Array, String, Number, BigInt)
  • ✅ Service layer
  • ✅ Validators
  • ✅ Factory
  • ✅ Integration tests
  • ✅ Error detection
  • ✅ Edge cases

Building

yarn build

Output in dist/ directory with TypeScript declarations.

How It Works

The Luhn Mod N algorithm:

  1. Creates a lookup table based on the base
  2. Processes digits from right to left
  3. Alternates between using the digit directly and using the lookup value
  4. Sums all values
  5. Calculates check digit: (sum * (base - 1)) % base

This algorithm detects:

  • Single digit errors
  • Most transposition errors (swapping adjacent digits)

Supported Bases

  • Base 2 (Binary)
  • Base 8 (Octal)
  • Base 10 (Decimal) - Default
  • Base 16 (Hexadecimal)
  • Any base from 2 to 16

License

MIT

Contributing

Contributions welcome! Please ensure:

  • All tests pass
  • Code follows existing patterns
  • New features include tests
  • TypeScript types are properly defined

Credits

Based on the Luhn Mod N algorithm:

  • Original: https://stackoverflow.com/a/23640453
  • Converted from: https://github.com/Digital-Defiance/Luhn-mod-n