@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
Maintainers
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 installQuick 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: trueUsage
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); // trueString 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); // trueNumber Service
import { LuhnServiceFactory } from 'luhn-mod-n-ts';
const numberService = LuhnServiceFactory.createNumberService();
numberService.calculate(123); // 0
numberService.append(123); // 1230
numberService.validate(1230); // trueBigInt 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); // trueReal-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); // 9876543217Hexadecimal 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 APIKey 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(): ReturnsCheckDigitService<number[]>createStringService(): ReturnsCheckDigitService<string>createNumberService(): ReturnsCheckDigitService<number>createBigIntService(): ReturnsCheckDigitService<bigint>
CheckDigitService
Generic service with three methods:
calculate(value: T, base?: number): number- Calculate check digitappend(value: T, base?: number): T- Append check digit to valuevalidate(value: T, base?: number): boolean- Validate value with check digit
Error Types
InvalidBaseError: Thrown when base is outside valid rangeInvalidInputError: Thrown for invalid input (e.g., empty string)
Testing
# Run all tests
yarn test
# Watch mode
yarn test:watch
# Coverage report
yarn test:coverageTest 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 buildOutput in dist/ directory with TypeScript declarations.
How It Works
The Luhn Mod N algorithm:
- Creates a lookup table based on the base
- Processes digits from right to left
- Alternates between using the digit directly and using the lookup value
- Sums all values
- 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
